lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 7b878cbaf91266faf773e2acfe1e3897c0f44fbc | 0 | PkayJava/MBaaS,PkayJava/MBaaS,PkayJava/MBaaS,PkayJava/MBaaS | package com.angkorteam.mbaas.server.controller;
import com.angkorteam.mbaas.model.entity.Tables;
import com.angkorteam.mbaas.model.entity.tables.ApplicationTable;
import com.angkorteam.mbaas.model.entity.tables.HostnameTable;
import com.angkorteam.mbaas.model.entity.tables.records.ApplicationRecord;
import com.angkorteam.mbaas.model.entity.tables.records.HostnameRecord;
import com.angkorteam.mbaas.plain.Identity;
import com.angkorteam.mbaas.plain.enums.TypeEnum;
import com.angkorteam.mbaas.plain.response.javascript.JavaScriptExecuteResponse;
import com.angkorteam.mbaas.server.Jdbc;
import com.angkorteam.mbaas.server.nashorn.JavaFilter;
import com.angkorteam.mbaas.server.nashorn.JavascripUtils;
import com.angkorteam.mbaas.server.spring.ApplicationContext;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sun.org.apache.xpath.internal.operations.Bool;
import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.jooq.DSLContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest;
import org.springframework.web.util.ContentCachingRequestWrapper;
import javax.script.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by socheat on 2/27/16.
*/
@Controller
@RequestMapping(path = "/javascript")
public class JavascriptController {
private static final DateFormat HTTP_DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
@Autowired
private ServletContext servletContext;
@Autowired
private Gson gson;
private Type mapType = new TypeToken<Map<String, Object>>() {
}.getType();
private Type listType = new TypeToken<List<Object>>() {
}.getType();
private static final Logger LOGGER = LoggerFactory.getLogger(com.angkorteam.mbaas.server.MBaaS.class);
@RequestMapping(path = "/**")
public ResponseEntity<JavaScriptExecuteResponse> execute(
HttpServletRequest req,
Identity identity
) throws IOException, ServletException {
byte[] requestBody = null;
if (ServletFileUpload.isMultipartContent(req)) {
requestBody = ((ContentCachingRequestWrapper) ((AbstractMultipartHttpServletRequest) ((FirewalledRequest) req).getRequest()).getRequest()).getContentAsByteArray();
} else {
requestBody = ((ContentCachingRequestWrapper) ((FirewalledRequest) req).getRequest()).getContentAsByteArray();
}
if (requestBody == null || requestBody.length == 0) {
requestBody = IOUtils.toByteArray(req.getInputStream());
}
// region stage, pathInfo
boolean stage = ServletRequestUtils.getBooleanParameter(req, "stage", false);
String pathInfo = req.getPathInfo().substring(11);
if ("".equals(pathInfo)) {
pathInfo = "/";
} else {
if (!"/".equals(pathInfo) && pathInfo.endsWith("/")) {
pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
}
}
String hostname = req.getServerName();
ApplicationContext applicationContext = ApplicationContext.get(this.servletContext);
DSLContext context = applicationContext.getDSLContext();
ApplicationTable applicationTable = Tables.APPLICATION.as("applicationTable");
HostnameTable hostnameTable = Tables.HOSTNAME.as("hostnameTable");
HostnameRecord hostnameRecord = context.select(hostnameTable.fields()).from(hostnameTable).where(hostnameTable.FQDN.eq(hostname)).fetchOneInto(hostnameTable);
if (hostnameRecord == null) {
return null;
}
ApplicationRecord applicationRecord = context.select(applicationTable.fields()).from(applicationTable).where(applicationTable.APPLICATION_ID.eq(hostnameRecord.getApplicationId())).fetchOneInto(applicationTable);
if (applicationRecord == null) {
return null;
}
String jdbcUrl = "jdbc:mysql://" + applicationRecord.getMysqlHostname() + ":" + applicationRecord.getMysqlPort() + "/" + applicationRecord.getMysqlDatabase() + "?" + applicationRecord.getMysqlExtra();
JdbcTemplate jdbcTemplate = applicationContext.getApplicationDataSource().getJdbcTemplate(applicationRecord.getCode(), jdbcUrl, applicationRecord.getMysqlUsername(), applicationRecord.getMysqlPassword());
if (jdbcTemplate == null) {
return null;
}
NamedParameterJdbcTemplate named = new NamedParameterJdbcTemplate(jdbcTemplate);
// endregion
// region restRecord
Map<String, Object> restRecord = null;
try {
restRecord = jdbcTemplate.queryForMap("SELECT * FROM " + Jdbc.REST + " WHERE " + Jdbc.Rest.PATH + " = ? AND " + Jdbc.Rest.METHOD + " = ?", pathInfo, StringUtils.upperCase(req.getMethod()));
} catch (EmptyResultDataAccessException e) {
}
if (restRecord == null) {
return null;
}
// endregion
// region http
Http http = null;
ScriptEngine scriptEngine = getScriptEngine(context);
String stageScript = (String) restRecord.get(Jdbc.Rest.STAGE_SCRIPT);
String script = (String) restRecord.get(Jdbc.Rest.SCRIPT);
if (stage) {
if ((stageScript == null || "".equals(stageScript))) {
return null;
} else {
try {
scriptEngine.eval(stageScript);
} catch (ScriptException e) {
return null;
}
Invocable invocable = (Invocable) scriptEngine;
http = invocable.getInterface(Http.class);
}
} else {
if (script == null || "".equals(script)) {
return null;
} else {
try {
scriptEngine.eval(script);
} catch (ScriptException e) {
return null;
}
Invocable invocable = (Invocable) scriptEngine;
http = invocable.getInterface(Http.class);
}
}
// endregion
// region nobody
List<String> headerIds = new ArrayList<>();
List<String> enumIds = new ArrayList<>();
List<String> queryIds = new ArrayList<>();
List<String> jsonIds = new ArrayList<>();
// endregion
// region requestHeaderRecords
List<Map<String, Object>> requestHeaderRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.REST_REQUEST_HEADER + " WHERE " + Jdbc.RestRequestHeader.REST_ID + " = ?", restRecord.get(Jdbc.Rest.REST_ID));
for (Map<String, Object> header : requestHeaderRecords) {
headerIds.add((String) header.get(Jdbc.RestRequestHeader.HTTP_HEADER_ID));
}
// endregion
// region responseHeaderRecords
List<Map<String, Object>> responseHeaderRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.REST_RESPONSE_HEADER + " WHERE " + Jdbc.RestResponseHeader.REST_ID + " = ?", restRecord.get(Jdbc.Rest.REST_ID));
for (Map<String, Object> header : responseHeaderRecords) {
headerIds.add((String) header.get(Jdbc.RestResponseHeader.HTTP_HEADER_ID));
}
// endregion
// region nobody
Map<String, Object> where = new HashMap<>();
where.put(Jdbc.HttpHeader.HTTP_HEADER_ID, headerIds);
List<Map<String, Object>> headerRecords = named.queryForList("SELECT * FROM " + Jdbc.HTTP_HEADER + " WHERE " + Jdbc.HttpHeader.HTTP_HEADER_ID + " in (:" + Jdbc.HttpHeader.HTTP_HEADER_ID + ")", where);
for (Map<String, Object> header : headerRecords) {
if (header.get(Jdbc.HttpHeader.ENUM_ID) != null && !"".equals(header.get(Jdbc.HttpHeader.ENUM_ID))) {
if (!enumIds.contains((String) header.get(Jdbc.HttpHeader.ENUM_ID))) {
enumIds.add((String) header.get(Jdbc.HttpHeader.ENUM_ID));
}
}
}
// endregion
// region headerDictionary
Map<String, Map<String, Object>> headerDictionary = new HashMap<>();
for (Map<String, Object> headerRecord : headerRecords) {
headerDictionary.put((String) headerRecord.get(Jdbc.HttpHeader.HTTP_HEADER_ID), headerRecord);
}
List<Map<String, Object>> requestQueryRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.REST_REQUEST_QUERY + " WHERE " + Jdbc.RestRequestQuery.REST_ID + " = ?", restRecord.get(Jdbc.Rest.REST_ID));
for (Map<String, Object> query : requestQueryRecords) {
if (!queryIds.contains((String) query.get(Jdbc.RestRequestQuery.HTTP_QUERY_ID))) {
queryIds.add((String) query.get(Jdbc.RestRequestQuery.HTTP_QUERY_ID));
}
}
// endregion
// region httpQueryDictionary
where.clear();
where.put(Jdbc.HttpQuery.HTTP_QUERY_ID, queryIds);
List<Map<String, Object>> queryRecords = named.queryForList("SELECT * FROM " + Jdbc.HTTP_QUERY + " WHERE " + Jdbc.HttpQuery.HTTP_QUERY_ID + " in (:" + Jdbc.HttpQuery.HTTP_QUERY_ID + ")", where);
Map<String, Map<String, Object>> httpQueryDictionary = new HashMap<>();
for (Map<String, Object> queryRecord : queryRecords) {
httpQueryDictionary.put((String) queryRecord.get(Jdbc.HttpQuery.HTTP_QUERY_ID), queryRecord);
}
for (Map<String, Object> query : queryRecords) {
if (query.get(Jdbc.HttpQuery.ENUM_ID) != null && !"".equals(query.get(Jdbc.HttpQuery.ENUM_ID))) {
if (!enumIds.contains((String) query.get(Jdbc.HttpQuery.ENUM_ID))) {
enumIds.add((String) query.get(Jdbc.HttpQuery.ENUM_ID));
}
}
}
// endregion
// region nobody
if (restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID))) {
if (!enumIds.contains((String) restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID))) {
enumIds.add((String) restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID));
}
}
String method = (String) restRecord.get(Jdbc.Rest.METHOD);
Map<String, Object> requestBodyRecord = null;
if (method.equals(HttpMethod.PUT.name()) || method.equals(HttpMethod.POST.name())) {
if (restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID))) {
if (!enumIds.contains((String) restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID))) {
enumIds.add((String) restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID));
}
}
if (restRecord.get(Jdbc.Rest.REQUEST_BODY_MAP_JSON_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.REQUEST_BODY_MAP_JSON_ID))) {
requestBodyRecord = jdbcTemplate.queryForMap("SELECT * FROM " + Jdbc.JSON + " WHERE " + Jdbc.Json.JSON_ID + " = ?", restRecord.get(Jdbc.Rest.REQUEST_BODY_MAP_JSON_ID));
}
}
Map<String, Object> responseBodyRecord = null;
if (restRecord.get(Jdbc.Rest.RESPONSE_BODY_MAP_JSON_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.RESPONSE_BODY_MAP_JSON_ID))) {
responseBodyRecord = jdbcTemplate.queryForMap("SELECT * FROM " + Jdbc.JSON + " WHERE " + Jdbc.Json.JSON_ID + " = ?", restRecord.get(Jdbc.Rest.RESPONSE_BODY_MAP_JSON_ID));
}
if (restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID))) {
if (!enumIds.contains((String) restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID))) {
enumIds.add((String) restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID));
}
}
if (requestBodyRecord != null) {
if (!jsonIds.contains((String) requestBodyRecord.get(Jdbc.Json.JSON_ID))) {
jsonIds.add((String) requestBodyRecord.get(Jdbc.Json.JSON_ID));
}
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", requestBodyRecord.get(Jdbc.Json.JSON_ID));
if (jsonFields != null && !jsonFields.isEmpty()) {
for (Map<String, Object> jsonField : jsonFields) {
processJsonField(jdbcTemplate, jsonIds, enumIds, jsonField);
}
}
}
if (responseBodyRecord != null) {
if (!jsonIds.contains((String) responseBodyRecord.get(Jdbc.Json.JSON_ID))) {
jsonIds.add((String) responseBodyRecord.get(Jdbc.Json.JSON_ID));
}
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", responseBodyRecord.get(Jdbc.Json.JSON_ID));
if (jsonFields != null && !jsonFields.isEmpty()) {
for (Map<String, Object> jsonField : jsonFields) {
processJsonField(jdbcTemplate, jsonIds, enumIds, jsonField);
}
}
}
List<Map<String, Object>> enumRecords = new ArrayList<>();
if (!enumIds.isEmpty()) {
where.clear();
where.put(Jdbc.Enum.ENUM_ID, enumIds);
enumRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.ENUM + " WHERE " + Jdbc.Enum.ENUM_ID + " in (:" + Jdbc.Enum.ENUM_ID + ")", where);
}
// endregion
// region enumDictionary
Map<String, Map<String, Object>> enumDictionary = new HashMap<>();
for (Map<String, Object> enumRecord : enumRecords) {
enumDictionary.put((String) enumRecord.get(Jdbc.Enum.ENUM_ID), enumRecord);
}
// endregion
// region nobody
List<Map<String, Object>> enumItemRecords = new ArrayList<>();
if (!enumIds.isEmpty()) {
where.clear();
where.put(Jdbc.EnumItem.ENUM_ID, enumIds);
enumItemRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.ENUM_ITEM + " WHERE " + Jdbc.EnumItem.ENUM_ID + " in (:" + Jdbc.EnumItem.ENUM_ID + ")", where);
}
// endregion
// region enumItemDictionary
Map<String, List<String>> enumItemDictionary = new HashMap<>();
for (Map<String, Object> enumItemRecord : enumItemRecords) {
String item = (String) enumItemRecord.get(Jdbc.EnumItem.VALUE);
if (!enumItemDictionary.containsKey((String) enumItemRecord.get(Jdbc.EnumItem.ENUM_ID))) {
List<String> items = new ArrayList<>();
items.add(item);
enumItemDictionary.put((String) enumItemRecord.get(Jdbc.EnumItem.ENUM_ID), items);
} else {
List<String> items = enumItemDictionary.get((String) enumItemRecord.get(Jdbc.EnumItem.ENUM_ID));
items.add(item);
}
}
// endregion
// region requestQueryDictionary
Map<String, List<String>> requestQueryDictionary = new HashMap<>();
String queryString = req.getQueryString();
if (queryString != null && !"".equals(queryString)) {
String[] params = StringUtils.split(queryString, '&');
for (String param : params) {
String tmp[] = StringUtils.split(param, '=');
String name = tmp[0];
String value = tmp[1];
if (!requestQueryDictionary.containsKey(name)) {
List<String> values = new ArrayList<>();
values.add(value);
requestQueryDictionary.put(name, values);
} else {
List<String> values = requestQueryDictionary.get(name);
values.add(value);
}
}
}
// endregion
// region requestHeaderDictionary
Map<String, List<String>> requestHeaderDictionary = new HashMap<>();
Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
Enumeration<String> tempValues = req.getHeaders(headerName);
List<String> headerValues = new ArrayList<>();
while (tempValues.hasMoreElements()) {
headerValues.add(tempValues.nextElement());
}
requestHeaderDictionary.put(headerName, headerValues);
}
// endregion
// region requestBodyJsonDictionary, requestBodyFormDictionary, requestBodyFormDataDictionary, requestBodyFormFileDictionary
Map<String, List<String>> requestBodyFormDictionary = new HashMap<>();
if (MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(req.getContentType())) {
String bodyString = "";
if (requestBody != null && requestBody.length > 0) {
bodyString = IOUtils.toString(requestBody, "UTF-8");
}
if (bodyString != null && !"".equals(bodyString)) {
String[] params = StringUtils.split(bodyString, '&');
for (String param : params) {
String tmp[] = StringUtils.split(param, '=');
String name = tmp[0];
String value = tmp[1];
if (!requestBodyFormDictionary.containsKey(name)) {
List<String> values = new ArrayList<>();
values.add(value);
requestBodyFormDictionary.put(name, values);
} else {
List<String> values = requestBodyFormDictionary.get(name);
values.add(value);
}
}
}
}
Map<String, List<String>> requestBodyFormDataDictionary = new HashMap<>();
Map<String, List<MultipartFile>> requestBodyFormFileDictionary = new HashMap<>();
if (ServletFileUpload.isMultipartContent(req)) {
MultipartHttpServletRequest request = (MultipartHttpServletRequest) ((FirewalledRequest) req).getRequest();
if (request.getParameterMap() != null && !request.getParameterMap().isEmpty()) {
for (Map.Entry<String, String[]> item : request.getParameterMap().entrySet()) {
if (!requestQueryDictionary.containsKey(item.getKey())) {
requestBodyFormDataDictionary.put(item.getKey(), Arrays.asList(item.getValue()));
}
}
}
if (request.getFileMap() != null && !request.getFileMap().isEmpty()) {
for (Map.Entry<String, MultipartFile> item : request.getFileMap().entrySet()) {
if (!requestBodyFormFileDictionary.containsKey(item.getKey())) {
List<MultipartFile> values = new ArrayList<>();
values.add(item.getValue());
requestBodyFormFileDictionary.put(item.getKey(), values);
} else {
List<MultipartFile> values = requestBodyFormFileDictionary.get(item.getKey());
values.add(item.getValue());
}
}
}
}
String json = "";
if (MediaType.APPLICATION_JSON_VALUE.equals(req.getContentType()) && !"".equals(json)) {
if (requestBody != null && requestBody.length > 0) {
json = new String(requestBody, "UTF-8");
}
}
// endregion
// region Validation Request Query Parameter
Map<String, String> requestQueryErrors = new HashMap<>();
for (Map<String, Object> requestQueryRecord : requestQueryRecords) {
String queryId = (String) requestQueryRecord.get(Jdbc.RestRequestQuery.HTTP_QUERY_ID);
Boolean required = (Boolean) requestQueryRecord.get(Jdbc.RestRequestQuery.REQUIRED);
Map<String, Object> httpQuery = httpQueryDictionary.get(queryId);
String name = (String) httpQuery.get(Jdbc.HttpQuery.NAME);
String enumId = (String) httpQuery.get(Jdbc.HttpQuery.ENUM_ID);
String type = (String) httpQuery.get(Jdbc.HttpQuery.TYPE);
String subType = (String) httpQuery.get(Jdbc.HttpQuery.SUB_TYPE);
if (required) {
// region required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestQueryDictionary.get(name) != null && !requestQueryDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestQueryErrors.put(name, "is invalid");
}
}
} else {
requestQueryErrors.put(name, "is required");
}
} else {
if (requestQueryDictionary.get(name) != null && !requestQueryDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else {
requestQueryErrors.put(name, "is required");
}
}
// endregion
} else {
// region not required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestQueryDictionary.get(name) != null && !requestQueryDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestQueryErrors.put(name, "is invalid");
}
}
}
} else {
if (requestQueryDictionary.get(name) != null && !requestQueryDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
}
}
// endregion
}
}
// endregion
// region Validation Request Header
Map<String, String> requestHeaderErrors = new HashMap<>();
for (Map<String, Object> requestHeaderRecord : requestHeaderRecords) {
String headerId = (String) requestHeaderRecord.get(Jdbc.RestRequestHeader.HTTP_HEADER_ID);
Boolean required = (Boolean) requestHeaderRecord.get(Jdbc.RestRequestHeader.REQUIRED);
Map<String, Object> httpHeader = headerDictionary.get(headerId);
String name = (String) httpHeader.get(Jdbc.HttpHeader.NAME);
String enumId = (String) httpHeader.get(Jdbc.HttpHeader.ENUM_ID);
String type = (String) httpHeader.get(Jdbc.HttpHeader.TYPE);
String subType = (String) httpHeader.get(Jdbc.HttpHeader.SUB_TYPE);
if (required) {
// region required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestHeaderDictionary.get(name) != null && !requestHeaderDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
HTTP_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else {
requestHeaderErrors.put(name, "is required");
}
} else {
if (requestHeaderDictionary.get(name) != null && !requestHeaderDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
HTTP_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else {
requestHeaderErrors.put(name, "is required");
}
}
// endregion
} else {
// region not required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestHeaderDictionary.get(name) != null && !requestHeaderDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
HTTP_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestHeaderErrors.put(name, "is invalid");
}
}
}
} else {
if (requestHeaderDictionary.get(name) != null && !requestHeaderDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
HTTP_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
}
}
// endregion
}
}
// endregion
// region Validation Request Body
Map<String, Object> requestBodyErrors = new HashMap<>();
if (method.equals(HttpMethod.PUT.name()) || method.equals(HttpMethod.POST.name())) {
String contentType = (String) restRecord.get(Jdbc.Rest.REQUEST_CONTENT_TYPE);
if (req.getContentType() == null || "".equals(req.getContentType())) {
return null;
}
if (!contentType.equals(req.getContentType())) {
return null;
}
if (contentType.equals(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
// region application/x-www-form-urlencoded
Boolean bodyRequired = (Boolean) restRecord.get(Jdbc.Rest.REQUEST_BODY_REQUIRED);
if (bodyRequired) {
if (requestBodyFormDictionary == null || requestBodyFormDictionary.isEmpty()) {
requestBodyErrors.put("requestBody", "is required");
}
}
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", requestBodyRecord.get(Jdbc.Json.JSON_ID));
for (Map<String, Object> jsonField : jsonFields) {
String name = (String) jsonField.get(Jdbc.JsonField.NAME);
boolean required = (boolean) jsonField.get(Jdbc.JsonField.REQUIRED);
String type = (String) jsonField.get(Jdbc.JsonField.TYPE);
String subType = (String) jsonField.get(Jdbc.JsonField.SUB_TYPE);
String enumId = (String) jsonField.get(Jdbc.JsonField.ENUM_ID);
if (required) {
// region required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestBodyFormDictionary.get(name) != null && !requestBodyFormDictionary.isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else {
requestBodyErrors.put(name, "is required");
}
} else {
if (requestBodyFormDictionary.get(name) != null && !requestBodyFormDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else {
requestBodyErrors.put(name, "is required");
}
}
// endregion
} else {
// region not required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestBodyFormDictionary.get(name) != null && !requestBodyFormDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
}
} else {
if (requestBodyFormDictionary.get(name) != null && !requestBodyFormDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
}
}
// endregion
}
}
// endregion
} else if (contentType.equals(MediaType.MULTIPART_FORM_DATA_VALUE)) {
// region multipart/form-data
Boolean bodyRequired = (Boolean) restRecord.get(Jdbc.Rest.REQUEST_BODY_REQUIRED);
if (bodyRequired) {
if ((requestBodyFormDataDictionary == null || requestBodyFormDataDictionary.isEmpty()) && (requestBodyFormFileDictionary == null || requestBodyFormFileDictionary.isEmpty())) {
requestBodyErrors.put("requestBody", "is required");
}
}
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", requestBodyRecord.get(Jdbc.Json.JSON_ID));
for (Map<String, Object> jsonField : jsonFields) {
String name = (String) jsonField.get(Jdbc.JsonField.NAME);
boolean required = (boolean) jsonField.get(Jdbc.JsonField.REQUIRED);
String type = (String) jsonField.get(Jdbc.JsonField.TYPE);
String subType = (String) jsonField.get(Jdbc.JsonField.SUB_TYPE);
String enumId = (String) jsonField.get(Jdbc.JsonField.ENUM_ID);
if (required) {
// region required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (TypeEnum.Boolean.getLiteral().equals(type)
|| TypeEnum.Long.getLiteral().equals(type)
|| TypeEnum.Double.getLiteral().equals(type)
|| TypeEnum.String.getLiteral().equals(type)
|| TypeEnum.Time.getLiteral().equals(type)
|| TypeEnum.Date.getLiteral().equals(type)
|| TypeEnum.DateTime.getLiteral().equals(type)
|| TypeEnum.Enum.getLiteral().equals(type)) {
if (requestBodyFormDataDictionary.get(name) != null && !requestBodyFormDataDictionary.isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else {
requestBodyErrors.put(name, "is required");
}
} else if (TypeEnum.File.getLiteral().equals(type)) {
if (requestBodyFormFileDictionary.get(name) != null && !requestBodyFormFileDictionary.isEmpty()) {
MultipartFile value = requestBodyFormFileDictionary.get(name).get(0);
if (value == null || value.isEmpty()) {
requestBodyErrors.put(name, "is required");
}
} else {
requestBodyErrors.put(name, "is required");
}
}
} else {
if (TypeEnum.Boolean.getLiteral().equals(subType)
|| TypeEnum.Long.getLiteral().equals(subType)
|| TypeEnum.Double.getLiteral().equals(subType)
|| TypeEnum.String.getLiteral().equals(subType)
|| TypeEnum.Time.getLiteral().equals(subType)
|| TypeEnum.Date.getLiteral().equals(subType)
|| TypeEnum.DateTime.getLiteral().equals(subType)
|| TypeEnum.Enum.getLiteral().equals(subType)) {
if (requestBodyFormDataDictionary.get(name) != null && !requestBodyFormDataDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else {
requestBodyErrors.put(name, "is required");
}
} else if (TypeEnum.File.getLiteral().equals(subType)) {
if (requestBodyFormFileDictionary.get(name) != null && !requestBodyFormFileDictionary.isEmpty()) {
for (MultipartFile value : requestBodyFormFileDictionary.get(name)) {
if (value == null || value.isEmpty()) {
requestBodyErrors.put(name, "is required");
break;
}
}
} else {
requestBodyErrors.put(name, "is required");
}
}
}
// endregion
} else {
// region not required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (TypeEnum.Boolean.getLiteral().equals(type)
|| TypeEnum.Long.getLiteral().equals(type)
|| TypeEnum.Double.getLiteral().equals(type)
|| TypeEnum.String.getLiteral().equals(type)
|| TypeEnum.Time.getLiteral().equals(type)
|| TypeEnum.Date.getLiteral().equals(type)
|| TypeEnum.DateTime.getLiteral().equals(type)
|| TypeEnum.Enum.getLiteral().equals(type)) {
if (requestBodyFormDataDictionary.get(name) != null && !requestBodyFormDataDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
}
} else if (TypeEnum.File.getLiteral().equals(type)) {
if (requestBodyFormFileDictionary.get(name) != null && !requestBodyFormFileDictionary.get(name).isEmpty()) {
MultipartFile value = requestBodyFormFileDictionary.get(name).get(0);
}
}
} else {
if (TypeEnum.Boolean.getLiteral().equals(subType)
|| TypeEnum.Long.getLiteral().equals(subType)
|| TypeEnum.Double.getLiteral().equals(subType)
|| TypeEnum.String.getLiteral().equals(subType)
|| TypeEnum.Time.getLiteral().equals(subType)
|| TypeEnum.Date.getLiteral().equals(subType)
|| TypeEnum.DateTime.getLiteral().equals(subType)
|| TypeEnum.Enum.getLiteral().equals(subType)) {
if (requestBodyFormDataDictionary.get(name) != null && !requestBodyFormDataDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
}
} else if (TypeEnum.File.getLiteral().equals(subType)) {
if (requestBodyFormFileDictionary != null && !requestBodyFormFileDictionary.isEmpty()) {
for (MultipartFile value : requestBodyFormFileDictionary.get(name)) {
}
}
}
}
// endregion
}
}
// endregion
} else if (contentType.equals(MediaType.APPLICATION_OCTET_STREAM_VALUE)) {
// region application/octet-stream
Boolean bodyRequired = (Boolean) restRecord.get(Jdbc.Rest.REQUEST_BODY_REQUIRED);
if (bodyRequired) {
if (requestBody == null || requestBody.length == 0) {
requestBodyErrors.put("requestBody", "is required");
}
}
// endregion
} else if (contentType.equals(MediaType.APPLICATION_JSON_VALUE)) {
String type = (String) restRecord.get(Jdbc.Rest.REQUEST_BODY_TYPE);
String enumId = (String) restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID);
Boolean bodyRequired = (Boolean) restRecord.get(Jdbc.Rest.REQUEST_BODY_REQUIRED);
if (bodyRequired && (json == null || "".equals(json))) {
requestBodyErrors.put("requestBody", "is required");
}
if (json != null && !"".equals(json)) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
try {
gson.fromJson(json, Boolean.class);
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
try {
gson.fromJson(json, Long.class);
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
try {
gson.fromJson(json, Double.class);
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
try {
gson.fromJson(json, String.class);
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
try {
String value = gson.fromJson(json, String.class);
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (JsonSyntaxException | ParseException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
try {
String value = gson.fromJson(json, String.class);
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (JsonSyntaxException | ParseException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
try {
String value = gson.fromJson(json, String.class);
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (JsonSyntaxException | ParseException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
Map<String, Object> enumRecord = enumDictionary.get(enumId);
String enumType = (String) enumRecord.get(Jdbc.Enum.TYPE);
List<String> enumValues = enumItemDictionary.get(enumId);
if (TypeEnum.Boolean.getLiteral().equals(enumType)) {
try {
String value = String.valueOf(gson.fromJson(json, Boolean.class));
if (!enumValues.contains(value)) {
requestBodyErrors.put("requestBody", "is invalid");
}
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Long.getLiteral().equals(enumType)) {
try {
String value = String.valueOf(gson.fromJson(json, Long.class));
if (!enumValues.contains(value)) {
requestBodyErrors.put("requestBody", "is invalid");
}
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Double.getLiteral().equals(enumType)) {
try {
String value = String.valueOf(gson.fromJson(json, Double.class));
if (!enumValues.contains(value)) {
requestBodyErrors.put("requestBody", "is invalid");
}
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Character.getLiteral().equals(enumType)
|| TypeEnum.String.getLiteral().equals(enumType)
|| TypeEnum.Time.getLiteral().equals(enumType)
|| TypeEnum.Date.getLiteral().equals(enumType)
|| TypeEnum.DateTime.getLiteral().equals(enumType)) {
try {
String value = gson.fromJson(json, String.class);
if (!enumValues.contains(value)) {
requestBodyErrors.put("requestBody", "is invalid");
}
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
}
} else if (TypeEnum.Map.getLiteral().equals(type)) {
String jsonId = (String) restRecord.get(Jdbc.Rest.REQUEST_BODY_MAP_JSON_ID);
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", jsonId);
Map<String, Object> jsonObject = gson.fromJson(json, mapType);
for (Map<String, Object> jsonField : jsonFields) {
validateJsonField(jdbcTemplate, requestBodyErrors, jsonObject, jsonField, enumItemDictionary);
}
// find map type
} else if (TypeEnum.List.getLiteral().equals(type)) {
// find subtype and repeat subtype checking again
}
}
}
}
// endregion
return null;
}
private void validateJsonField(JdbcTemplate jdbcTemplate, Map<String, Object> error, Map<String, Object> json, Map<String, Object> jsonField, Map<String, List<String>> enumItemDictionary) {
String type = (String) jsonField.get(Jdbc.JsonField.TYPE);
String name = (String) jsonField.get(Jdbc.JsonField.NAME);
String enumId = (String) jsonField.get(Jdbc.JsonField.ENUM_ID);
String jsonId = (String) jsonField.get(Jdbc.JsonField.MAP_JSON_ID);
String subType = (String) jsonField.get(Jdbc.JsonField.SUB_TYPE);
Boolean required = (Boolean) jsonField.get(Jdbc.JsonField.REQUIRED);
if (required) {
// region required
if (TypeEnum.Boolean.getLiteral().equals(type)) {
Boolean value = (Boolean) json.get(name);
if (value == null) {
error.put(name, "is required");
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
Long value = (Long) json.get(name);
if (value == null) {
error.put(name, "is required");
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
Double value = (Double) json.get(name);
if (value == null) {
error.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = (String) json.get(name);
if (value == null || "".equals(value)) {
error.put(name, "is required");
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = (String) json.get(name);
if (value == null || "".equals(value)) {
error.put(name, "is required");
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = (String) json.get(name);
if (value == null || "".equals(value)) {
error.put(name, "is required");
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = (String) json.get(name);
if (value == null || "".equals(value)) {
error.put(name, "is required");
} else {
List<String> enumItemValues = enumItemDictionary.get(enumId);
if (!enumItemValues.contains(value)) {
error.put(name, "is invalid");
}
}
} else if (TypeEnum.Map.getLiteral().equals(type)) {
Map<String, Object> fieldJson = (Map<String, Object>) json.get(name);
Map<String, Object> fieldError = new HashMap<>();
List<Map<String, Object>> fieldJsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", fieldJson.get(Jdbc.JsonField.JSON_ID));
for (Map<String, Object> fieldJsonField : fieldJsonFields) {
validateJsonField(jdbcTemplate, fieldError, fieldJson, fieldJsonField, enumItemDictionary);
}
} else if (TypeEnum.List.getLiteral().equals(type)) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
List<Boolean> values = (List<Boolean>) json.get(name);
for (Boolean value : values) {
if (value == null) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
List<Long> values = (List<Long>) json.get(name);
for (Long value : values) {
if (value == null) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
List<Double> values = (List<Double>) json.get(name);
for (Double value : values) {
if (value == null) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
List<String> values = (List<String>) json.get(name);
for (String value : values) {
if (value == null || "".equals(value)) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
List<String> values = (List<String>) json.get(name);
for (String value : values) {
if (value == null || "".equals(value)) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
List<String> values = (List<String>) json.get(name);
for (String value : values) {
if (value == null || "".equals(value)) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
List<String> values = (List<String>) json.get(name);
for (String value : values) {
if (value == null || "".equals(value)) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
List<String> values = (List<String>) json.get(name);
for (String value : values) {
if (value == null || "".equals(value)) {
error.put(name, "is required");
break;
} else {
List<String> enumItemValues = enumItemDictionary.get(enumId);
if (!enumItemValues.contains(value)) {
error.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Map.getLiteral().equals(subType)) {
Map<String, Object> fieldJson = (Map<String, Object>) json.get(name);
Map<String, Object> fieldError = new HashMap<>();
error.put(name, fieldError);
List<Map<String, Object>> fieldJsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", fieldJson.get(Jdbc.JsonField.JSON_ID));
for (Map<String, Object> fieldJsonField : fieldJsonFields) {
validateJsonField(jdbcTemplate, fieldError, fieldJson, fieldJsonField, enumItemDictionary);
}
}
}
// endregion
} else {
// region not required
if (TypeEnum.Time.getLiteral().equals(type)) {
String value = (String) json.get(name);
if (value == null || "".equals(value)) {
error.put(name, "is required");
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = (String) json.get(name);
if (value == null || "".equals(value)) {
error.put(name, "is required");
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = (String) json.get(name);
if (value == null || "".equals(value)) {
error.put(name, "is required");
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = (String) json.get(name);
if (value == null || "".equals(value)) {
error.put(name, "is required");
} else {
List<String> enumItemValues = enumItemDictionary.get(enumId);
if (!enumItemValues.contains(value)) {
error.put(name, "is invalid");
}
}
} else if (TypeEnum.Map.getLiteral().equals(type)) {
Map<String, Object> fieldJson = (Map<String, Object>) json.get(name);
Map<String, Object> fieldError = new HashMap<>();
List<Map<String, Object>> fieldJsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", fieldJson.get(Jdbc.JsonField.JSON_ID));
for (Map<String, Object> fieldJsonField : fieldJsonFields) {
validateJsonField(jdbcTemplate, fieldError, fieldJson, fieldJsonField, enumItemDictionary);
}
} else if (TypeEnum.List.getLiteral().equals(type)) {
if (TypeEnum.Time.getLiteral().equals(subType)) {
List<String> values = (List<String>) json.get(name);
for (String value : values) {
if (value == null || "".equals(value)) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
List<String> values = (List<String>) json.get(name);
for (String value : values) {
if (value == null || "".equals(value)) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
List<String> values = (List<String>) json.get(name);
for (String value : values) {
if (value == null || "".equals(value)) {
error.put(name, "is required");
break;
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
List<String> values = (List<String>) json.get(name);
for (String value : values) {
if (value == null || "".equals(value)) {
error.put(name, "is required");
break;
} else {
List<String> enumItemValues = enumItemDictionary.get(enumId);
if (!enumItemValues.contains(value)) {
error.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Map.getLiteral().equals(subType)) {
Map<String, Object> fieldJson = (Map<String, Object>) json.get(name);
Map<String, Object> fieldError = new HashMap<>();
error.put(name, fieldError);
List<Map<String, Object>> fieldJsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", fieldJson.get(Jdbc.JsonField.JSON_ID));
for (Map<String, Object> fieldJsonField : fieldJsonFields) {
validateJsonField(jdbcTemplate, fieldError, fieldJson, fieldJsonField, enumItemDictionary);
}
}
}
// endregion
}
}
/**
* process to build enumId
*
* @param jdbcTemplate
* @param jsonIdList
* @param enumIdList
* @param jsonField
*/
private void processJsonField(JdbcTemplate jdbcTemplate, List<String> jsonIdList, List<String> enumIdList, Map<String, Object> jsonField) {
if (jsonField.get(Jdbc.JsonField.ENUM_ID) != null && !"".equals(jsonField.get(Jdbc.JsonField.ENUM_ID))) {
if (!enumIdList.contains((String) jsonField.get(Jdbc.JsonField.ENUM_ID))) {
enumIdList.add((String) jsonField.get(Jdbc.JsonField.ENUM_ID));
}
}
if (jsonField.get(Jdbc.JsonField.MAP_JSON_ID) != null && !"".equals(jsonField.get(Jdbc.JsonField.MAP_JSON_ID))) {
if (!jsonIdList.contains((String) jsonField.get(Jdbc.JsonField.MAP_JSON_ID))) {
jsonIdList.add((String) jsonField.get(Jdbc.JsonField.MAP_JSON_ID));
List<Map<String, Object>> fields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", jsonField.get(Jdbc.JsonField.MAP_JSON_ID));
if (fields != null && !fields.isEmpty()) {
for (Map<String, Object> field : fields) {
processJsonField(jdbcTemplate, jsonIdList, enumIdList, field);
}
}
}
}
}
private ScriptEngine getScriptEngine(DSLContext context) {
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new JavaFilter(context));
Bindings bindings = engine.createBindings();
engine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
JavascripUtils.eval(engine);
return engine;
}
private Object parseBody(Object body) {
if (body instanceof JSObject) {
JSObject js = (JSObject) body;
if (js.isStrictFunction() || js.isFunction()) {
return null;
} else if (js.isArray()) {
return js.values();
} else {
Map<String, Object> result = new LinkedHashMap<>();
for (String key : js.keySet()) {
result.put(key, js.getMember(key));
}
return result;
}
} else {
return body;
}
}
protected ResponseEntity<JavaScriptExecuteResponse> returnThrowable(Throwable throwable) {
LOGGER.info(throwable.getMessage());
if (throwable instanceof BadCredentialsException) {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setHttpCode(HttpStatus.UNAUTHORIZED.value());
response.setResult(HttpStatus.UNAUTHORIZED.getReasonPhrase());
return ResponseEntity.ok(response);
} else {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setHttpCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setResult(throwable.getMessage());
return ResponseEntity.ok(response);
}
}
protected ResponseEntity<JavaScriptExecuteResponse> returnResponse(boolean found, boolean error, Throwable throwable, Object responseBody) {
if (!found) {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setHttpCode(HttpStatus.METHOD_NOT_ALLOWED.value());
return ResponseEntity.ok(response);
} else {
if (error) {
return returnThrowable(throwable);
} else {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setData(parseBody(responseBody));
return ResponseEntity.ok(response);
}
}
}
protected ResponseEntity<JavaScriptExecuteResponse> returnMethodNotAllowed() {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setHttpCode(HttpStatus.METHOD_NOT_ALLOWED.value());
response.setResult(HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
return ResponseEntity.ok(response);
}
public interface Http {
Object http(com.angkorteam.mbaas.server.nashorn.Request request, Map<String, Object> requestBody);
}
}
| mbaas-server/src/main/java/com/angkorteam/mbaas/server/controller/JavascriptController.java | package com.angkorteam.mbaas.server.controller;
import com.angkorteam.mbaas.model.entity.Tables;
import com.angkorteam.mbaas.model.entity.tables.ApplicationTable;
import com.angkorteam.mbaas.model.entity.tables.HostnameTable;
import com.angkorteam.mbaas.model.entity.tables.records.ApplicationRecord;
import com.angkorteam.mbaas.model.entity.tables.records.HostnameRecord;
import com.angkorteam.mbaas.plain.Identity;
import com.angkorteam.mbaas.plain.enums.TypeEnum;
import com.angkorteam.mbaas.plain.response.javascript.JavaScriptExecuteResponse;
import com.angkorteam.mbaas.server.Jdbc;
import com.angkorteam.mbaas.server.nashorn.JavaFilter;
import com.angkorteam.mbaas.server.nashorn.JavascripUtils;
import com.angkorteam.mbaas.server.spring.ApplicationContext;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sun.org.apache.xpath.internal.operations.Bool;
import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.jooq.DSLContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest;
import org.springframework.web.util.ContentCachingRequestWrapper;
import javax.script.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by socheat on 2/27/16.
*/
@Controller
@RequestMapping(path = "/javascript")
public class JavascriptController {
private static final DateFormat HTTP_DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
@Autowired
private ServletContext servletContext;
@Autowired
private Gson gson;
private Type mapType = new TypeToken<Map<String, Object>>() {
}.getType();
private Type listType = new TypeToken<List<Object>>() {
}.getType();
private static final Logger LOGGER = LoggerFactory.getLogger(com.angkorteam.mbaas.server.MBaaS.class);
@RequestMapping(path = "/**")
public ResponseEntity<JavaScriptExecuteResponse> execute(
HttpServletRequest req,
Identity identity
) throws IOException, ServletException {
byte[] requestBody = null;
if (ServletFileUpload.isMultipartContent(req)) {
requestBody = ((ContentCachingRequestWrapper) ((AbstractMultipartHttpServletRequest) ((FirewalledRequest) req).getRequest()).getRequest()).getContentAsByteArray();
} else {
requestBody = ((ContentCachingRequestWrapper) ((FirewalledRequest) req).getRequest()).getContentAsByteArray();
}
if (requestBody == null || requestBody.length == 0) {
requestBody = IOUtils.toByteArray(req.getInputStream());
}
// region stage, pathInfo
boolean stage = ServletRequestUtils.getBooleanParameter(req, "stage", false);
String pathInfo = req.getPathInfo().substring(11);
if ("".equals(pathInfo)) {
pathInfo = "/";
} else {
if (!"/".equals(pathInfo) && pathInfo.endsWith("/")) {
pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
}
}
String hostname = req.getServerName();
ApplicationContext applicationContext = ApplicationContext.get(this.servletContext);
DSLContext context = applicationContext.getDSLContext();
ApplicationTable applicationTable = Tables.APPLICATION.as("applicationTable");
HostnameTable hostnameTable = Tables.HOSTNAME.as("hostnameTable");
HostnameRecord hostnameRecord = context.select(hostnameTable.fields()).from(hostnameTable).where(hostnameTable.FQDN.eq(hostname)).fetchOneInto(hostnameTable);
if (hostnameRecord == null) {
return null;
}
ApplicationRecord applicationRecord = context.select(applicationTable.fields()).from(applicationTable).where(applicationTable.APPLICATION_ID.eq(hostnameRecord.getApplicationId())).fetchOneInto(applicationTable);
if (applicationRecord == null) {
return null;
}
String jdbcUrl = "jdbc:mysql://" + applicationRecord.getMysqlHostname() + ":" + applicationRecord.getMysqlPort() + "/" + applicationRecord.getMysqlDatabase() + "?" + applicationRecord.getMysqlExtra();
JdbcTemplate jdbcTemplate = applicationContext.getApplicationDataSource().getJdbcTemplate(applicationRecord.getCode(), jdbcUrl, applicationRecord.getMysqlUsername(), applicationRecord.getMysqlPassword());
if (jdbcTemplate == null) {
return null;
}
NamedParameterJdbcTemplate named = new NamedParameterJdbcTemplate(jdbcTemplate);
// endregion
// region restRecord
Map<String, Object> restRecord = null;
try {
restRecord = jdbcTemplate.queryForMap("SELECT * FROM " + Jdbc.REST + " WHERE " + Jdbc.Rest.PATH + " = ? AND " + Jdbc.Rest.METHOD + " = ?", pathInfo, StringUtils.upperCase(req.getMethod()));
} catch (EmptyResultDataAccessException e) {
}
if (restRecord == null) {
return null;
}
// endregion
// region http
Http http = null;
ScriptEngine scriptEngine = getScriptEngine(context);
String stageScript = (String) restRecord.get(Jdbc.Rest.STAGE_SCRIPT);
String script = (String) restRecord.get(Jdbc.Rest.SCRIPT);
if (stage) {
if ((stageScript == null || "".equals(stageScript))) {
return null;
} else {
try {
scriptEngine.eval(stageScript);
} catch (ScriptException e) {
return null;
}
Invocable invocable = (Invocable) scriptEngine;
http = invocable.getInterface(Http.class);
}
} else {
if (script == null || "".equals(script)) {
return null;
} else {
try {
scriptEngine.eval(script);
} catch (ScriptException e) {
return null;
}
Invocable invocable = (Invocable) scriptEngine;
http = invocable.getInterface(Http.class);
}
}
// endregion
// region nobody
List<String> headerIds = new ArrayList<>();
List<String> enumIds = new ArrayList<>();
List<String> queryIds = new ArrayList<>();
List<String> jsonIds = new ArrayList<>();
// endregion
// region requestHeaderRecords
List<Map<String, Object>> requestHeaderRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.REST_REQUEST_HEADER + " WHERE " + Jdbc.RestRequestHeader.REST_ID + " = ?", restRecord.get(Jdbc.Rest.REST_ID));
for (Map<String, Object> header : requestHeaderRecords) {
headerIds.add((String) header.get(Jdbc.RestRequestHeader.HTTP_HEADER_ID));
}
// endregion
// region responseHeaderRecords
List<Map<String, Object>> responseHeaderRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.REST_RESPONSE_HEADER + " WHERE " + Jdbc.RestResponseHeader.REST_ID + " = ?", restRecord.get(Jdbc.Rest.REST_ID));
for (Map<String, Object> header : responseHeaderRecords) {
headerIds.add((String) header.get(Jdbc.RestResponseHeader.HTTP_HEADER_ID));
}
// endregion
// region nobody
Map<String, Object> where = new HashMap<>();
where.put(Jdbc.HttpHeader.HTTP_HEADER_ID, headerIds);
List<Map<String, Object>> headerRecords = named.queryForList("SELECT * FROM " + Jdbc.HTTP_HEADER + " WHERE " + Jdbc.HttpHeader.HTTP_HEADER_ID + " in (:" + Jdbc.HttpHeader.HTTP_HEADER_ID + ")", where);
for (Map<String, Object> header : headerRecords) {
if (header.get(Jdbc.HttpHeader.ENUM_ID) != null && !"".equals(header.get(Jdbc.HttpHeader.ENUM_ID))) {
if (!enumIds.contains((String) header.get(Jdbc.HttpHeader.ENUM_ID))) {
enumIds.add((String) header.get(Jdbc.HttpHeader.ENUM_ID));
}
}
}
// endregion
// region headerDictionary
Map<String, Map<String, Object>> headerDictionary = new HashMap<>();
for (Map<String, Object> headerRecord : headerRecords) {
headerDictionary.put((String) headerRecord.get(Jdbc.HttpHeader.HTTP_HEADER_ID), headerRecord);
}
List<Map<String, Object>> requestQueryRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.REST_REQUEST_QUERY + " WHERE " + Jdbc.RestRequestQuery.REST_ID + " = ?", restRecord.get(Jdbc.Rest.REST_ID));
for (Map<String, Object> query : requestQueryRecords) {
if (!queryIds.contains((String) query.get(Jdbc.RestRequestQuery.HTTP_QUERY_ID))) {
queryIds.add((String) query.get(Jdbc.RestRequestQuery.HTTP_QUERY_ID));
}
}
// endregion
// region httpQueryDictionary
where.clear();
where.put(Jdbc.HttpQuery.HTTP_QUERY_ID, queryIds);
List<Map<String, Object>> queryRecords = named.queryForList("SELECT * FROM " + Jdbc.HTTP_QUERY + " WHERE " + Jdbc.HttpQuery.HTTP_QUERY_ID + " in (:" + Jdbc.HttpQuery.HTTP_QUERY_ID + ")", where);
Map<String, Map<String, Object>> httpQueryDictionary = new HashMap<>();
for (Map<String, Object> queryRecord : queryRecords) {
httpQueryDictionary.put((String) queryRecord.get(Jdbc.HttpQuery.HTTP_QUERY_ID), queryRecord);
}
for (Map<String, Object> query : queryRecords) {
if (query.get(Jdbc.HttpQuery.ENUM_ID) != null && !"".equals(query.get(Jdbc.HttpQuery.ENUM_ID))) {
if (!enumIds.contains((String) query.get(Jdbc.HttpQuery.ENUM_ID))) {
enumIds.add((String) query.get(Jdbc.HttpQuery.ENUM_ID));
}
}
}
// endregion
// region nobody
if (restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID))) {
if (!enumIds.contains((String) restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID))) {
enumIds.add((String) restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID));
}
}
String method = (String) restRecord.get(Jdbc.Rest.METHOD);
Map<String, Object> requestBodyRecord = null;
if (method.equals(HttpMethod.PUT.name()) || method.equals(HttpMethod.POST.name())) {
if (restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID))) {
if (!enumIds.contains((String) restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID))) {
enumIds.add((String) restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID));
}
}
if (restRecord.get(Jdbc.Rest.REQUEST_BODY_MAP_JSON_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.REQUEST_BODY_MAP_JSON_ID))) {
requestBodyRecord = jdbcTemplate.queryForMap("SELECT * FROM " + Jdbc.JSON + " WHERE " + Jdbc.Json.JSON_ID + " = ?", restRecord.get(Jdbc.Rest.REQUEST_BODY_MAP_JSON_ID));
}
}
Map<String, Object> responseBodyRecord = null;
if (restRecord.get(Jdbc.Rest.RESPONSE_BODY_MAP_JSON_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.RESPONSE_BODY_MAP_JSON_ID))) {
responseBodyRecord = jdbcTemplate.queryForMap("SELECT * FROM " + Jdbc.JSON + " WHERE " + Jdbc.Json.JSON_ID + " = ?", restRecord.get(Jdbc.Rest.RESPONSE_BODY_MAP_JSON_ID));
}
if (restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID) != null && !"".equals(restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID))) {
if (!enumIds.contains((String) restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID))) {
enumIds.add((String) restRecord.get(Jdbc.Rest.RESPONSE_BODY_ENUM_ID));
}
}
if (requestBodyRecord != null) {
if (!jsonIds.contains((String) requestBodyRecord.get(Jdbc.Json.JSON_ID))) {
jsonIds.add((String) requestBodyRecord.get(Jdbc.Json.JSON_ID));
}
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", requestBodyRecord.get(Jdbc.Json.JSON_ID));
if (jsonFields != null && !jsonFields.isEmpty()) {
for (Map<String, Object> jsonField : jsonFields) {
processJsonField(jdbcTemplate, jsonIds, enumIds, jsonField);
}
}
}
if (responseBodyRecord != null) {
if (!jsonIds.contains((String) responseBodyRecord.get(Jdbc.Json.JSON_ID))) {
jsonIds.add((String) responseBodyRecord.get(Jdbc.Json.JSON_ID));
}
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", responseBodyRecord.get(Jdbc.Json.JSON_ID));
if (jsonFields != null && !jsonFields.isEmpty()) {
for (Map<String, Object> jsonField : jsonFields) {
processJsonField(jdbcTemplate, jsonIds, enumIds, jsonField);
}
}
}
List<Map<String, Object>> enumRecords = new ArrayList<>();
if (!enumIds.isEmpty()) {
where.clear();
where.put(Jdbc.Enum.ENUM_ID, enumIds);
enumRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.ENUM + " WHERE " + Jdbc.Enum.ENUM_ID + " in (:" + Jdbc.Enum.ENUM_ID + ")", where);
}
// endregion
// region enumDictionary
Map<String, Map<String, Object>> enumDictionary = new HashMap<>();
for (Map<String, Object> enumRecord : enumRecords) {
enumDictionary.put((String) enumRecord.get(Jdbc.Enum.ENUM_ID), enumRecord);
}
// endregion
// region nobody
List<Map<String, Object>> enumItemRecords = new ArrayList<>();
if (!enumIds.isEmpty()) {
where.clear();
where.put(Jdbc.EnumItem.ENUM_ID, enumIds);
enumItemRecords = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.ENUM_ITEM + " WHERE " + Jdbc.EnumItem.ENUM_ID + " in (:" + Jdbc.EnumItem.ENUM_ID + ")", where);
}
// endregion
// region enumItemDictionary
Map<String, List<String>> enumItemDictionary = new HashMap<>();
for (Map<String, Object> enumItemRecord : enumItemRecords) {
String item = (String) enumItemRecord.get(Jdbc.EnumItem.VALUE);
if (!enumItemDictionary.containsKey((String) enumItemRecord.get(Jdbc.EnumItem.ENUM_ID))) {
List<String> items = new ArrayList<>();
items.add(item);
enumItemDictionary.put((String) enumItemRecord.get(Jdbc.EnumItem.ENUM_ID), items);
} else {
List<String> items = enumItemDictionary.get((String) enumItemRecord.get(Jdbc.EnumItem.ENUM_ID));
items.add(item);
}
}
// endregion
// region requestQueryDictionary
Map<String, List<String>> requestQueryDictionary = new HashMap<>();
String queryString = req.getQueryString();
if (queryString != null && !"".equals(queryString)) {
String[] params = StringUtils.split(queryString, '&');
for (String param : params) {
String tmp[] = StringUtils.split(param, '=');
String name = tmp[0];
String value = tmp[1];
if (!requestQueryDictionary.containsKey(name)) {
List<String> values = new ArrayList<>();
values.add(value);
requestQueryDictionary.put(name, values);
} else {
List<String> values = requestQueryDictionary.get(name);
values.add(value);
}
}
}
// endregion
// region requestHeaderDictionary
Map<String, List<String>> requestHeaderDictionary = new HashMap<>();
Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
Enumeration<String> tempValues = req.getHeaders(headerName);
List<String> headerValues = new ArrayList<>();
while (tempValues.hasMoreElements()) {
headerValues.add(tempValues.nextElement());
}
requestHeaderDictionary.put(headerName, headerValues);
}
// endregion
// region requestBodyJsonDictionary, requestBodyFormDictionary, requestBodyFormDataDictionary, requestBodyFormFileDictionary
Map<String, List<String>> requestBodyFormDictionary = new HashMap<>();
if (MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(req.getContentType())) {
String bodyString = "";
if (requestBody != null && requestBody.length > 0) {
bodyString = IOUtils.toString(requestBody, "UTF-8");
}
if (bodyString != null && !"".equals(bodyString)) {
String[] params = StringUtils.split(bodyString, '&');
for (String param : params) {
String tmp[] = StringUtils.split(param, '=');
String name = tmp[0];
String value = tmp[1];
if (!requestBodyFormDictionary.containsKey(name)) {
List<String> values = new ArrayList<>();
values.add(value);
requestBodyFormDictionary.put(name, values);
} else {
List<String> values = requestBodyFormDictionary.get(name);
values.add(value);
}
}
}
}
Map<String, List<String>> requestBodyFormDataDictionary = new HashMap<>();
Map<String, List<MultipartFile>> requestBodyFormFileDictionary = new HashMap<>();
if (ServletFileUpload.isMultipartContent(req)) {
MultipartHttpServletRequest request = (MultipartHttpServletRequest) ((FirewalledRequest) req).getRequest();
if (request.getParameterMap() != null && !request.getParameterMap().isEmpty()) {
for (Map.Entry<String, String[]> item : request.getParameterMap().entrySet()) {
if (!requestQueryDictionary.containsKey(item.getKey())) {
requestBodyFormDataDictionary.put(item.getKey(), Arrays.asList(item.getValue()));
}
}
}
if (request.getFileMap() != null && !request.getFileMap().isEmpty()) {
for (Map.Entry<String, MultipartFile> item : request.getFileMap().entrySet()) {
if (!requestBodyFormFileDictionary.containsKey(item.getKey())) {
List<MultipartFile> values = new ArrayList<>();
values.add(item.getValue());
requestBodyFormFileDictionary.put(item.getKey(), values);
} else {
List<MultipartFile> values = requestBodyFormFileDictionary.get(item.getKey());
values.add(item.getValue());
}
}
}
}
String json = "";
if (MediaType.APPLICATION_JSON_VALUE.equals(req.getContentType()) && !"".equals(json)) {
if (requestBody != null && requestBody.length > 0) {
json = new String(requestBody, "UTF-8");
}
}
// endregion
// region Validation Request Query Parameter
Map<String, String> requestQueryErrors = new HashMap<>();
for (Map<String, Object> requestQueryRecord : requestQueryRecords) {
String queryId = (String) requestQueryRecord.get(Jdbc.RestRequestQuery.HTTP_QUERY_ID);
Boolean required = (Boolean) requestQueryRecord.get(Jdbc.RestRequestQuery.REQUIRED);
Map<String, Object> httpQuery = httpQueryDictionary.get(queryId);
String name = (String) httpQuery.get(Jdbc.HttpQuery.NAME);
String enumId = (String) httpQuery.get(Jdbc.HttpQuery.ENUM_ID);
String type = (String) httpQuery.get(Jdbc.HttpQuery.TYPE);
String subType = (String) httpQuery.get(Jdbc.HttpQuery.SUB_TYPE);
if (required) {
// region required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestQueryDictionary.get(name) != null && !requestQueryDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestQueryErrors.put(name, "is invalid");
}
}
} else {
requestQueryErrors.put(name, "is required");
}
} else {
if (requestQueryDictionary.get(name) != null && !requestQueryDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestQueryErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else {
requestQueryErrors.put(name, "is required");
}
}
// endregion
} else {
// region not required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestQueryDictionary.get(name) != null && !requestQueryDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestQueryDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestQueryErrors.put(name, "is invalid");
}
}
}
} else {
if (requestQueryDictionary.get(name) != null && !requestQueryDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestQueryDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestQueryErrors.put(name, "is invalid");
break;
}
}
}
}
}
// endregion
}
}
// endregion
// region Validation Request Header
Map<String, String> requestHeaderErrors = new HashMap<>();
for (Map<String, Object> requestHeaderRecord : requestHeaderRecords) {
String headerId = (String) requestHeaderRecord.get(Jdbc.RestRequestHeader.HTTP_HEADER_ID);
Boolean required = (Boolean) requestHeaderRecord.get(Jdbc.RestRequestHeader.REQUIRED);
Map<String, Object> httpHeader = headerDictionary.get(headerId);
String name = (String) httpHeader.get(Jdbc.HttpHeader.NAME);
String enumId = (String) httpHeader.get(Jdbc.HttpHeader.ENUM_ID);
String type = (String) httpHeader.get(Jdbc.HttpHeader.TYPE);
String subType = (String) httpHeader.get(Jdbc.HttpHeader.SUB_TYPE);
if (required) {
// region required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestHeaderDictionary.get(name) != null && !requestHeaderDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
} else {
try {
HTTP_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else {
requestHeaderErrors.put(name, "is required");
}
} else {
if (requestHeaderDictionary.get(name) != null && !requestHeaderDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestHeaderErrors.put(name, "is required");
break;
} else {
try {
HTTP_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else {
requestHeaderErrors.put(name, "is required");
}
}
// endregion
} else {
// region not required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestHeaderDictionary.get(name) != null && !requestHeaderDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
HTTP_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestHeaderDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestHeaderErrors.put(name, "is invalid");
}
}
}
} else {
if (requestHeaderDictionary.get(name) != null && !requestHeaderDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
HTTP_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestHeaderDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestHeaderErrors.put(name, "is invalid");
break;
}
}
}
}
}
// endregion
}
}
// endregion
// region Validation Request Body
Map<String, Object> requestBodyErrors = new HashMap<>();
if (method.equals(HttpMethod.PUT.name()) || method.equals(HttpMethod.POST.name())) {
String contentType = (String) restRecord.get(Jdbc.Rest.REQUEST_CONTENT_TYPE);
if (req.getContentType() == null || "".equals(req.getContentType())) {
return null;
}
if (!contentType.equals(req.getContentType())) {
return null;
}
if (contentType.equals(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
// region application/x-www-form-urlencoded
Boolean bodyRequired = (Boolean) restRecord.get(Jdbc.Rest.REQUEST_BODY_REQUIRED);
if (bodyRequired) {
if (requestBodyFormDictionary == null || requestBodyFormDictionary.isEmpty()) {
requestBodyErrors.put("requestBody", "is required");
}
}
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", requestBodyRecord.get(Jdbc.Json.JSON_ID));
for (Map<String, Object> jsonField : jsonFields) {
String name = (String) jsonField.get(Jdbc.JsonField.NAME);
boolean required = (boolean) jsonField.get(Jdbc.JsonField.REQUIRED);
String type = (String) jsonField.get(Jdbc.JsonField.TYPE);
String subType = (String) jsonField.get(Jdbc.JsonField.SUB_TYPE);
String enumId = (String) jsonField.get(Jdbc.JsonField.ENUM_ID);
if (required) {
// region required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestBodyFormDictionary.get(name) != null && !requestBodyFormDictionary.isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else {
requestBodyErrors.put(name, "is required");
}
} else {
if (requestBodyFormDictionary.get(name) != null && !requestBodyFormDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else {
requestBodyErrors.put(name, "is required");
}
}
// endregion
} else {
// region not required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (requestBodyFormDictionary.get(name) != null && !requestBodyFormDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestBodyFormDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
}
} else {
if (requestBodyFormDictionary.get(name) != null && !requestBodyFormDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestBodyFormDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
}
}
// endregion
}
}
// endregion
} else if (contentType.equals(MediaType.MULTIPART_FORM_DATA_VALUE)) {
// region multipart/form-data
Boolean bodyRequired = (Boolean) restRecord.get(Jdbc.Rest.REQUEST_BODY_REQUIRED);
if (bodyRequired) {
if ((requestBodyFormDataDictionary == null || requestBodyFormDataDictionary.isEmpty()) && (requestBodyFormFileDictionary == null || requestBodyFormFileDictionary.isEmpty())) {
requestBodyErrors.put("requestBody", "is required");
}
}
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", requestBodyRecord.get(Jdbc.Json.JSON_ID));
for (Map<String, Object> jsonField : jsonFields) {
String name = (String) jsonField.get(Jdbc.JsonField.NAME);
boolean required = (boolean) jsonField.get(Jdbc.JsonField.REQUIRED);
String type = (String) jsonField.get(Jdbc.JsonField.TYPE);
String subType = (String) jsonField.get(Jdbc.JsonField.SUB_TYPE);
String enumId = (String) jsonField.get(Jdbc.JsonField.ENUM_ID);
if (required) {
// region required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (TypeEnum.Boolean.getLiteral().equals(type)
|| TypeEnum.Long.getLiteral().equals(type)
|| TypeEnum.Double.getLiteral().equals(type)
|| TypeEnum.String.getLiteral().equals(type)
|| TypeEnum.Time.getLiteral().equals(type)
|| TypeEnum.Date.getLiteral().equals(type)
|| TypeEnum.DateTime.getLiteral().equals(type)
|| TypeEnum.Enum.getLiteral().equals(type)) {
if (requestBodyFormDataDictionary.get(name) != null && !requestBodyFormDataDictionary.isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else {
requestBodyErrors.put(name, "is required");
}
} else if (TypeEnum.File.getLiteral().equals(type)) {
if (requestBodyFormFileDictionary.get(name) != null && !requestBodyFormFileDictionary.isEmpty()) {
MultipartFile value = requestBodyFormFileDictionary.get(name).get(0);
if (value == null || value.isEmpty()) {
requestBodyErrors.put(name, "is required");
}
} else {
requestBodyErrors.put(name, "is required");
}
}
} else {
if (TypeEnum.Boolean.getLiteral().equals(subType)
|| TypeEnum.Long.getLiteral().equals(subType)
|| TypeEnum.Double.getLiteral().equals(subType)
|| TypeEnum.String.getLiteral().equals(subType)
|| TypeEnum.Time.getLiteral().equals(subType)
|| TypeEnum.Date.getLiteral().equals(subType)
|| TypeEnum.DateTime.getLiteral().equals(subType)
|| TypeEnum.Enum.getLiteral().equals(subType)) {
if (requestBodyFormDataDictionary.get(name) != null && !requestBodyFormDataDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
requestBodyErrors.put(name, "is required");
break;
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else {
requestBodyErrors.put(name, "is required");
}
} else if (TypeEnum.File.getLiteral().equals(subType)) {
if (requestBodyFormFileDictionary.get(name) != null && !requestBodyFormFileDictionary.isEmpty()) {
for (MultipartFile value : requestBodyFormFileDictionary.get(name)) {
if (value == null || value.isEmpty()) {
requestBodyErrors.put(name, "is required");
break;
}
}
} else {
requestBodyErrors.put(name, "is required");
}
}
}
// endregion
} else {
// region not required
if (!TypeEnum.List.getLiteral().equals(type)) {
if (TypeEnum.Boolean.getLiteral().equals(type)
|| TypeEnum.Long.getLiteral().equals(type)
|| TypeEnum.Double.getLiteral().equals(type)
|| TypeEnum.String.getLiteral().equals(type)
|| TypeEnum.Time.getLiteral().equals(type)
|| TypeEnum.Date.getLiteral().equals(type)
|| TypeEnum.DateTime.getLiteral().equals(type)
|| TypeEnum.Enum.getLiteral().equals(type)) {
if (requestBodyFormDataDictionary.get(name) != null && !requestBodyFormDataDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
}
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = requestBodyFormDataDictionary.get(name).get(0);
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
}
}
}
} else if (TypeEnum.File.getLiteral().equals(type)) {
if (requestBodyFormFileDictionary.get(name) != null && !requestBodyFormFileDictionary.get(name).isEmpty()) {
MultipartFile value = requestBodyFormFileDictionary.get(name).get(0);
}
}
} else {
if (TypeEnum.Boolean.getLiteral().equals(subType)
|| TypeEnum.Long.getLiteral().equals(subType)
|| TypeEnum.Double.getLiteral().equals(subType)
|| TypeEnum.String.getLiteral().equals(subType)
|| TypeEnum.Time.getLiteral().equals(subType)
|| TypeEnum.Date.getLiteral().equals(subType)
|| TypeEnum.DateTime.getLiteral().equals(subType)
|| TypeEnum.Enum.getLiteral().equals(subType)) {
if (requestBodyFormDataDictionary.get(name) != null && !requestBodyFormDataDictionary.get(name).isEmpty()) {
if (TypeEnum.Boolean.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
if (!"true".equals(value) || !"false".equals(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Long.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Long.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Double.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
Double.valueOf(value);
} catch (NumberFormatException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.String.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
}
}
} else if (TypeEnum.Time.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Date.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.DateTime.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
if (value == null || "".equals(value)) {
} else {
try {
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (ParseException e) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
} else if (TypeEnum.Enum.getLiteral().equals(subType)) {
for (String value : requestBodyFormDataDictionary.get(name)) {
List<String> enumItems = enumItemDictionary.get(enumId);
if (!enumItems.contains(value)) {
requestBodyErrors.put(name, "is invalid");
break;
}
}
}
}
} else if (TypeEnum.File.getLiteral().equals(subType)) {
if (requestBodyFormFileDictionary != null && !requestBodyFormFileDictionary.isEmpty()) {
for (MultipartFile value : requestBodyFormFileDictionary.get(name)) {
}
}
}
}
// endregion
}
}
// endregion
} else if (contentType.equals(MediaType.APPLICATION_OCTET_STREAM_VALUE)) {
// region application/octet-stream
Boolean bodyRequired = (Boolean) restRecord.get(Jdbc.Rest.REQUEST_BODY_REQUIRED);
if (bodyRequired) {
if (requestBody == null || requestBody.length == 0) {
requestBodyErrors.put("requestBody", "is required");
}
}
// endregion
} else if (contentType.equals(MediaType.APPLICATION_JSON_VALUE)) {
String type = (String) restRecord.get(Jdbc.Rest.REQUEST_BODY_TYPE);
String enumId = (String) restRecord.get(Jdbc.Rest.REQUEST_BODY_ENUM_ID);
Boolean bodyRequired = (Boolean) restRecord.get(Jdbc.Rest.REQUEST_BODY_REQUIRED);
if (bodyRequired && (json == null || "".equals(json))) {
requestBodyErrors.put("requestBody", "is required");
}
if (json != null && !"".equals(json)) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
try {
gson.fromJson(json, Boolean.class);
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
try {
gson.fromJson(json, Long.class);
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
try {
gson.fromJson(json, Double.class);
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.String.getLiteral().equals(type)) {
try {
gson.fromJson(json, String.class);
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
try {
String value = gson.fromJson(json, String.class);
DateFormatUtils.ISO_DATE_FORMAT.parse(value);
} catch (JsonSyntaxException | ParseException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
try {
String value = gson.fromJson(json, String.class);
DateFormatUtils.ISO_TIME_NO_T_FORMAT.parse(value);
} catch (JsonSyntaxException | ParseException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
try {
String value = gson.fromJson(json, String.class);
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.parse(value);
} catch (JsonSyntaxException | ParseException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
Map<String, Object> enumRecord = enumDictionary.get(enumId);
String enumType = (String) enumRecord.get(Jdbc.Enum.TYPE);
List<String> enumValues = enumItemDictionary.get(enumId);
if (TypeEnum.Boolean.getLiteral().equals(enumType)) {
try {
String value = String.valueOf(gson.fromJson(json, Boolean.class));
if (!enumValues.contains(value)) {
requestBodyErrors.put("requestBody", "is invalid");
}
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Long.getLiteral().equals(enumType)) {
try {
String value = String.valueOf(gson.fromJson(json, Long.class));
if (!enumValues.contains(value)) {
requestBodyErrors.put("requestBody", "is invalid");
}
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Double.getLiteral().equals(enumType)) {
try {
String value = String.valueOf(gson.fromJson(json, Double.class));
if (!enumValues.contains(value)) {
requestBodyErrors.put("requestBody", "is invalid");
}
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
} else if (TypeEnum.Character.getLiteral().equals(enumType)
|| TypeEnum.String.getLiteral().equals(enumType)
|| TypeEnum.Time.getLiteral().equals(enumType)
|| TypeEnum.Date.getLiteral().equals(enumType)
|| TypeEnum.DateTime.getLiteral().equals(enumType)) {
try {
String value = gson.fromJson(json, String.class);
if (!enumValues.contains(value)) {
requestBodyErrors.put("requestBody", "is invalid");
}
} catch (JsonSyntaxException e) {
requestBodyErrors.put("requestBody", "is invalid");
}
}
} else if (TypeEnum.Map.getLiteral().equals(type)) {
String jsonId = (String) restRecord.get(Jdbc.Rest.REQUEST_BODY_MAP_JSON_ID);
List<Map<String, Object>> jsonFields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", jsonId);
Map<String, Object> jsonObject = gson.fromJson(json, mapType);
for (Map<String, Object> jsonField : jsonFields) {
validateJsonField(requestBodyErrors, jdbcTemplate, jsonObject, jsonField);
}
// find map type
} else if (TypeEnum.List.getLiteral().equals(type)) {
// find subtype and repeat subtype checking again
}
}
}
}
// endregion
return null;
}
private void validateJsonField(Map<String, Object> errors, JdbcTemplate jdbcTemplate, Map<String, Object> parentJson, Map<String, Object> jsonField) {
String type = (String) jsonField.get(Jdbc.JsonField.TYPE);
String name = (String) jsonField.get(Jdbc.JsonField.NAME);
String enumId = (String) jsonField.get(Jdbc.JsonField.ENUM_ID);
String jsonId = (String) jsonField.get(Jdbc.JsonField.MAP_JSON_ID);
String subType = (String) jsonField.get(Jdbc.JsonField.SUB_TYPE);
Boolean required = (Boolean) jsonField.get(Jdbc.JsonField.REQUIRED);
if (required) {
if (TypeEnum.Boolean.getLiteral().equals(type)) {
Boolean value = (Boolean) parentJson.get(name);
if (value == null) {
errors.put(name, "is required");
}
} else if (TypeEnum.Long.getLiteral().equals(type)) {
Long value = (Long) parentJson.get(name);
if (value == null) {
errors.put(name, "is required");
}
} else if (TypeEnum.Double.getLiteral().equals(type)) {
Double value = (Double) parentJson.get(name);
if (value == null) {
errors.put(name, "is required");
}
} else if (TypeEnum.Time.getLiteral().equals(type)) {
String value = (String) parentJson.get(name);
if (value == null || "".equals(value)) {
errors.put(name, "is required");
}
} else if (TypeEnum.Date.getLiteral().equals(type)) {
String value = (String) parentJson.get(name);
if (value == null || "".equals(value)) {
errors.put(name, "is required");
}
} else if (TypeEnum.DateTime.getLiteral().equals(type)) {
String value = (String) parentJson.get(name);
if (value == null || "".equals(value)) {
errors.put(name, "is required");
}
} else if (TypeEnum.Enum.getLiteral().equals(type)) {
String value = (String) parentJson.get(name);
if (value == null || "".equals(value)) {
errors.put(name, "is required");
}
} else if (TypeEnum.Map.getLiteral().equals(type)) {
Map<String, Object> childJson = (Map<String, Object>) parentJson.get(name);
} else if (TypeEnum.List.getLiteral().equals(type)) {
List<Object> values = (List<Object>) parentJson.get(name);
for (Object value : values) {
}
}
} else {
}
}
/**
* process to build enumId
*
* @param jdbcTemplate
* @param jsonIdList
* @param enumIdList
* @param jsonField
*/
private void processJsonField(JdbcTemplate jdbcTemplate, List<String> jsonIdList, List<String> enumIdList, Map<String, Object> jsonField) {
if (jsonField.get(Jdbc.JsonField.ENUM_ID) != null && !"".equals(jsonField.get(Jdbc.JsonField.ENUM_ID))) {
if (!enumIdList.contains((String) jsonField.get(Jdbc.JsonField.ENUM_ID))) {
enumIdList.add((String) jsonField.get(Jdbc.JsonField.ENUM_ID));
}
}
if (jsonField.get(Jdbc.JsonField.MAP_JSON_ID) != null && !"".equals(jsonField.get(Jdbc.JsonField.MAP_JSON_ID))) {
if (!jsonIdList.contains((String) jsonField.get(Jdbc.JsonField.MAP_JSON_ID))) {
jsonIdList.add((String) jsonField.get(Jdbc.JsonField.MAP_JSON_ID));
List<Map<String, Object>> fields = jdbcTemplate.queryForList("SELECT * FROM " + Jdbc.JSON_FIELD + " WHERE " + Jdbc.JsonField.JSON_ID + " = ?", jsonField.get(Jdbc.JsonField.MAP_JSON_ID));
if (fields != null && !fields.isEmpty()) {
for (Map<String, Object> field : fields) {
processJsonField(jdbcTemplate, jsonIdList, enumIdList, field);
}
}
}
}
}
private ScriptEngine getScriptEngine(DSLContext context) {
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new JavaFilter(context));
Bindings bindings = engine.createBindings();
engine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
JavascripUtils.eval(engine);
return engine;
}
private Object parseBody(Object body) {
if (body instanceof JSObject) {
JSObject js = (JSObject) body;
if (js.isStrictFunction() || js.isFunction()) {
return null;
} else if (js.isArray()) {
return js.values();
} else {
Map<String, Object> result = new LinkedHashMap<>();
for (String key : js.keySet()) {
result.put(key, js.getMember(key));
}
return result;
}
} else {
return body;
}
}
protected ResponseEntity<JavaScriptExecuteResponse> returnThrowable(Throwable throwable) {
LOGGER.info(throwable.getMessage());
if (throwable instanceof BadCredentialsException) {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setHttpCode(HttpStatus.UNAUTHORIZED.value());
response.setResult(HttpStatus.UNAUTHORIZED.getReasonPhrase());
return ResponseEntity.ok(response);
} else {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setHttpCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setResult(throwable.getMessage());
return ResponseEntity.ok(response);
}
}
protected ResponseEntity<JavaScriptExecuteResponse> returnResponse(boolean found, boolean error, Throwable throwable, Object responseBody) {
if (!found) {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setHttpCode(HttpStatus.METHOD_NOT_ALLOWED.value());
return ResponseEntity.ok(response);
} else {
if (error) {
return returnThrowable(throwable);
} else {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setData(parseBody(responseBody));
return ResponseEntity.ok(response);
}
}
}
protected ResponseEntity<JavaScriptExecuteResponse> returnMethodNotAllowed() {
JavaScriptExecuteResponse response = new JavaScriptExecuteResponse();
response.setHttpCode(HttpStatus.METHOD_NOT_ALLOWED.value());
response.setResult(HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
return ResponseEntity.ok(response);
}
public interface Http {
Object http(com.angkorteam.mbaas.server.nashorn.Request request, Map<String, Object> requestBody);
}
}
| javascript controller improve request body json validation
| mbaas-server/src/main/java/com/angkorteam/mbaas/server/controller/JavascriptController.java | javascript controller improve request body json validation |
|
Java | apache-2.0 | 03d6350e4b3c7e23e3cc84bf3f261f2c53b5b1e9 | 0 | spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.method.support;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.HandlerMethod;
/**
* Provides a method for invoking the handler method for a given request after resolving its method argument
* values through registered {@link HandlerMethodArgumentResolver}s.
*
* <p>Argument resolution often requires a {@link WebDataBinder} for data binding or for type conversion.
* Use the {@link #setDataBinderFactory(WebDataBinderFactory)} property to supply a binder factory to pass to
* argument resolvers.
*
* <p>Use {@link #setHandlerMethodArgumentResolvers(HandlerMethodArgumentResolverComposite)} to customize
* the list of argument resolvers.
*
* @author Rossen Stoyanchev
* @since 3.1
*/
public class InvocableHandlerMethod extends HandlerMethod {
private HandlerMethodArgumentResolverComposite argumentResolvers = new HandlerMethodArgumentResolverComposite();
private WebDataBinderFactory dataBinderFactory;
private ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
/**
* Constructs a new handler method with the given bean instance and method.
* @param bean the bean instance
* @param method the method
*/
public InvocableHandlerMethod(Object bean, Method method) {
super(bean, method);
}
/**
* Constructs a new handler method with the given bean instance, method name and parameters.
* @param bean the object bean
* @param methodName the method name
* @param parameterTypes the method parameter types
* @throws NoSuchMethodException when the method cannot be found
*/
public InvocableHandlerMethod(
Object bean, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException {
super(bean, methodName, parameterTypes);
}
/**
* Sets the {@link WebDataBinderFactory} to be passed to argument resolvers allowing them to create
* a {@link WebDataBinder} for data binding and type conversion purposes.
* @param dataBinderFactory the data binder factory.
*/
public void setDataBinderFactory(WebDataBinderFactory dataBinderFactory) {
this.dataBinderFactory = dataBinderFactory;
}
/**
* Set {@link HandlerMethodArgumentResolver}s to use to use for resolving method argument values.
*/
public void setHandlerMethodArgumentResolvers(HandlerMethodArgumentResolverComposite argumentResolvers) {
this.argumentResolvers = argumentResolvers;
}
/**
* Set the ParameterNameDiscoverer for resolving parameter names when needed (e.g. default request attribute name).
* <p>Default is an {@link org.springframework.core.LocalVariableTableParameterNameDiscoverer} instance.
*/
public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) {
this.parameterNameDiscoverer = parameterNameDiscoverer;
}
/**
* Invoke the method after resolving its argument values in the context of the given request. <p>Argument
* values are commonly resolved through {@link HandlerMethodArgumentResolver}s. The {@code provideArgs}
* parameter however may supply argument values to be used directly, i.e. without argument resolution.
* Examples of provided argument values include a {@link WebDataBinder}, a {@link SessionStatus}, or
* a thrown exception instance. Provided argument values are checked before argument resolvers.
*
* @param request the current request
* @param mavContainer the ModelAndViewContainer for this request
* @param providedArgs "given" arguments matched by type, not resolved
* @return the raw value returned by the invoked method
* @exception Exception raised if no suitable argument resolver can be found, or the method raised an exception
*/
public final Object invokeForRequest(NativeWebRequest request,
ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {
Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
if (logger.isTraceEnabled()) {
StringBuilder builder = new StringBuilder("Invoking [");
builder.append(this.getMethod().getName()).append("] method with arguments ");
builder.append(Arrays.asList(args));
logger.trace(builder.toString());
}
Object returnValue = invoke(args);
if (logger.isTraceEnabled()) {
logger.trace("Method [" + this.getMethod().getName() + "] returned [" + returnValue + "]");
}
return returnValue;
}
/**
* Get the method argument values for the current request.
*/
private Object[] getMethodArgumentValues(
NativeWebRequest request, ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {
MethodParameter[] parameters = getMethodParameters();
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
MethodParameter parameter = parameters[i];
parameter.initParameterNameDiscovery(parameterNameDiscoverer);
GenericTypeResolver.resolveParameterType(parameter, getBean().getClass());
args[i] = resolveProvidedArgument(parameter, providedArgs);
if (args[i] != null) {
continue;
}
if (argumentResolvers.supportsParameter(parameter)) {
try {
args[i] = argumentResolvers.resolveArgument(parameter, mavContainer, request, dataBinderFactory);
continue;
} catch (Exception ex) {
if (logger.isTraceEnabled()) {
logger.trace(getArgumentResolutionErrorMessage("Error resolving argument", i), ex);
}
throw ex;
}
}
if (args[i] == null) {
String msg = getArgumentResolutionErrorMessage("No suitable resolver for argument", i);
throw new IllegalStateException(msg);
}
}
return args;
}
private String getArgumentResolutionErrorMessage(String message, int index) {
MethodParameter param = getMethodParameters()[index];
message += " [" + index + "] [type=" + param.getParameterType().getName() + "]";
return getDetailedErrorMessage(message);
}
/**
* Adds HandlerMethod details such as the controller type and method signature to the given error message.
* @param message error message to append the HandlerMethod details to
*/
protected String getDetailedErrorMessage(String message) {
StringBuilder sb = new StringBuilder(message).append("\n");
sb.append("HandlerMethod details: \n");
sb.append("Controller [").append(getBeanType().getName()).append("]\n");
sb.append("Method [").append(getBridgedMethod().toGenericString()).append("]\n");
return sb.toString();
}
/**
* Attempt to resolve a method parameter from the list of provided argument values.
*/
private Object resolveProvidedArgument(MethodParameter parameter, Object... providedArgs) {
if (providedArgs == null) {
return null;
}
for (Object providedArg : providedArgs) {
if (parameter.getParameterType().isInstance(providedArg)) {
return providedArg;
}
}
return null;
}
/**
* Invoke the handler method with the given argument values.
*/
private Object invoke(Object... args) throws Exception {
ReflectionUtils.makeAccessible(this.getBridgedMethod());
try {
return getBridgedMethod().invoke(getBean(), args);
}
catch (IllegalArgumentException e) {
String msg = getInvocationErrorMessage(e.getMessage(), args);
throw new IllegalArgumentException(msg, e);
}
catch (InvocationTargetException e) {
// Unwrap for HandlerExceptionResolvers ...
Throwable targetException = e.getTargetException();
if (targetException instanceof RuntimeException) {
throw (RuntimeException) targetException;
}
else if (targetException instanceof Error) {
throw (Error) targetException;
}
else if (targetException instanceof Exception) {
throw (Exception) targetException;
}
else {
String msg = getInvocationErrorMessage("Failed to invoke controller method", args);
throw new IllegalStateException(msg, targetException);
}
}
}
private String getInvocationErrorMessage(String message, Object[] resolvedArgs) {
StringBuilder sb = new StringBuilder(getDetailedErrorMessage(message));
sb.append("Resolved arguments: \n");
for (int i=0; i < resolvedArgs.length; i++) {
sb.append("[").append(i).append("] ");
if (resolvedArgs[i] == null) {
sb.append("[null] \n");
}
else {
sb.append("[type=").append(resolvedArgs[i].getClass().getName()).append("] ");
sb.append("[value=").append(resolvedArgs[i]).append("]\n");
}
}
return sb.toString();
}
}
| spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.method.support;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.HandlerMethod;
/**
* Provides a method for invoking the handler method for a given request after resolving its method argument
* values through registered {@link HandlerMethodArgumentResolver}s.
*
* <p>Argument resolution often requires a {@link WebDataBinder} for data binding or for type conversion.
* Use the {@link #setDataBinderFactory(WebDataBinderFactory)} property to supply a binder factory to pass to
* argument resolvers.
*
* <p>Use {@link #setHandlerMethodArgumentResolvers(HandlerMethodArgumentResolverComposite)} to customize
* the list of argument resolvers.
*
* @author Rossen Stoyanchev
* @since 3.1
*/
public class InvocableHandlerMethod extends HandlerMethod {
private HandlerMethodArgumentResolverComposite argumentResolvers = new HandlerMethodArgumentResolverComposite();
private WebDataBinderFactory dataBinderFactory;
private ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
/**
* Constructs a new handler method with the given bean instance and method.
* @param bean the bean instance
* @param method the method
*/
public InvocableHandlerMethod(Object bean, Method method) {
super(bean, method);
}
/**
* Constructs a new handler method with the given bean instance, method name and parameters.
* @param bean the object bean
* @param methodName the method name
* @param parameterTypes the method parameter types
* @throws NoSuchMethodException when the method cannot be found
*/
public InvocableHandlerMethod(
Object bean, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException {
super(bean, methodName, parameterTypes);
}
/**
* Sets the {@link WebDataBinderFactory} to be passed to argument resolvers allowing them to create
* a {@link WebDataBinder} for data binding and type conversion purposes.
* @param dataBinderFactory the data binder factory.
*/
public void setDataBinderFactory(WebDataBinderFactory dataBinderFactory) {
this.dataBinderFactory = dataBinderFactory;
}
/**
* Set {@link HandlerMethodArgumentResolver}s to use to use for resolving method argument values.
*/
public void setHandlerMethodArgumentResolvers(HandlerMethodArgumentResolverComposite argumentResolvers) {
this.argumentResolvers = argumentResolvers;
}
/**
* Set the ParameterNameDiscoverer for resolving parameter names when needed (e.g. default request attribute name).
* <p>Default is an {@link org.springframework.core.LocalVariableTableParameterNameDiscoverer} instance.
*/
public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) {
this.parameterNameDiscoverer = parameterNameDiscoverer;
}
/**
* Invoke the method after resolving its argument values in the context of the given request. <p>Argument
* values are commonly resolved through {@link HandlerMethodArgumentResolver}s. The {@code provideArgs}
* parameter however may supply argument values to be used directly, i.e. without argument resolution.
* Examples of provided argument values include a {@link WebDataBinder}, a {@link SessionStatus}, or
* a thrown exception instance. Provided argument values are checked before argument resolvers.
*
* @param request the current request
* @param mavContainer the ModelAndViewContainer for this request
* @param providedArgs "given" arguments matched by type, not resolved
* @return the raw value returned by the invoked method
* @exception Exception raised if no suitable argument resolver can be found, or the method raised an exception
*/
public final Object invokeForRequest(NativeWebRequest request,
ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {
Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
if (logger.isTraceEnabled()) {
StringBuilder builder = new StringBuilder("Invoking [");
builder.append(this.getMethod().getName()).append("] method with arguments ");
builder.append(Arrays.asList(args));
logger.trace(builder.toString());
}
Object returnValue = invoke(args);
if (logger.isTraceEnabled()) {
logger.trace("Method [" + this.getMethod().getName() + "] returned [" + returnValue + "]");
}
return returnValue;
}
/**
* Get the method argument values for the current request.
*/
private Object[] getMethodArgumentValues(
NativeWebRequest request, ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {
MethodParameter[] parameters = getMethodParameters();
Object[] args = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
MethodParameter parameter = parameters[i];
parameter.initParameterNameDiscovery(parameterNameDiscoverer);
GenericTypeResolver.resolveParameterType(parameter, getBean().getClass());
args[i] = resolveProvidedArgument(parameter, providedArgs);
if (args[i] != null) {
continue;
}
if (argumentResolvers.supportsParameter(parameter)) {
try {
args[i] = argumentResolvers.resolveArgument(parameter, mavContainer, request, dataBinderFactory);
continue;
} catch (Exception ex) {
if (logger.isTraceEnabled()) {
logger.trace(getArgumentResolutionErrorMessage("Error resolving argument", i), ex);
}
throw ex;
}
}
if (args[i] == null) {
String msg = getArgumentResolutionErrorMessage("No suitable resolver for argument", i);
throw new IllegalStateException(msg);
}
}
return args;
}
private String getArgumentResolutionErrorMessage(String message, int index) {
MethodParameter param = getMethodParameters()[index];
message += " [" + index + "] [type=" + param.getParameterType().getName() + "]";
return getDetailedErrorMessage(message);
}
/**
* Adds HandlerMethod details such as the controller type and method signature to the given error message.
* @param message error message to append the HandlerMethod details to
*/
protected String getDetailedErrorMessage(String message) {
StringBuilder sb = new StringBuilder(message).append("\n");
sb.append("HandlerMethod details: \n");
sb.append("Controller [").append(getBeanType().getName()).append("]\n");
sb.append("Method [").append(getBridgedMethod().toGenericString()).append("]\n");
return sb.toString();
}
/**
* Attempt to resolve a method parameter from the list of provided argument values.
*/
private Object resolveProvidedArgument(MethodParameter parameter, Object... providedArgs) {
if (providedArgs == null || parameter.hasParameterAnnotations()) {
return null;
}
for (Object providedArg : providedArgs) {
if (parameter.getParameterType().isInstance(providedArg)) {
return providedArg;
}
}
return null;
}
/**
* Invoke the handler method with the given argument values.
*/
private Object invoke(Object... args) throws Exception {
ReflectionUtils.makeAccessible(this.getBridgedMethod());
try {
return getBridgedMethod().invoke(getBean(), args);
}
catch (IllegalArgumentException e) {
String msg = getInvocationErrorMessage(e.getMessage(), args);
throw new IllegalArgumentException(msg, e);
}
catch (InvocationTargetException e) {
// Unwrap for HandlerExceptionResolvers ...
Throwable targetException = e.getTargetException();
if (targetException instanceof RuntimeException) {
throw (RuntimeException) targetException;
}
else if (targetException instanceof Error) {
throw (Error) targetException;
}
else if (targetException instanceof Exception) {
throw (Exception) targetException;
}
else {
String msg = getInvocationErrorMessage("Failed to invoke controller method", args);
throw new IllegalStateException(msg, targetException);
}
}
}
private String getInvocationErrorMessage(String message, Object[] resolvedArgs) {
StringBuilder sb = new StringBuilder(getDetailedErrorMessage(message));
sb.append("Resolved arguments: \n");
for (int i=0; i < resolvedArgs.length; i++) {
sb.append("[").append(i).append("] ");
if (resolvedArgs[i] == null) {
sb.append("[null] \n");
}
else {
sb.append("[type=").append(resolvedArgs[i].getClass().getName()).append("] ");
sb.append("[value=").append(resolvedArgs[i]).append("]\n");
}
}
return sb.toString();
}
}
| Fix issue with resolution of WebDataBinder argument
There is usually not need to put annotations on a WebDataBinder
argument in an `@InitBinder` method. However, the presence of any
annotation prevented the successful resolution of the argument.
This fix addresses the issue.
Issue: SPR-8946
| spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java | Fix issue with resolution of WebDataBinder argument |
|
Java | apache-2.0 | 452627e0e24a67026a391fc79e333235e852d81a | 0 | GerritCodeReview/plugins_serviceuser,GerritCodeReview/plugins_serviceuser,GerritCodeReview/plugins_serviceuser,GerritCodeReview/plugins_serviceuser,GerritCodeReview/plugins_serviceuser | // Copyright (C) 2014 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.serviceuser.client;
import com.google.gerrit.plugin.client.Plugin;
import com.google.gerrit.plugin.client.rpc.RestApi;
import com.google.gerrit.plugin.client.screen.Screen;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.InlineHyperlink;
import com.google.gwt.user.client.ui.VerticalPanel;
public class ServiceUserListScreen extends VerticalPanel {
static class Factory implements Screen.EntryPoint {
@Override
public void onLoad(Screen screen) {
screen.setPageTitle("Service Users");
screen.show(new ServiceUserListScreen());
}
}
ServiceUserListScreen() {
setStyleName("serviceuser-panel");
new RestApi("config").id("server").view(Plugin.get().getPluginName(), "serviceusers")
.get(NativeMap.copyKeysIntoChildren("username",
new AsyncCallback<NativeMap<ServiceUserInfo>>() {
@Override
public void onSuccess(NativeMap<ServiceUserInfo> info) {
display(info);
}
@Override
public void onFailure(Throwable caught) {
// never invoked
}
}));
}
private void display(NativeMap<ServiceUserInfo> info) {
int columns = 6;
FlexTable t = new FlexTable();
t.setStyleName("serviceuser-serviceUserTable");
FlexCellFormatter fmt = t.getFlexCellFormatter();
for (int c = 0; c < columns; c++) {
fmt.addStyleName(0, c, "dataHeader");
fmt.addStyleName(0, c, "topMostCell");
}
fmt.addStyleName(0, 0, "leftMostCell");
t.setText(0, 0, "Username");
t.setText(0, 1, "Full Name");
t.setText(0, 2, "Email");
t.setText(0, 3, "Created By");
t.setText(0, 4, "Created At");
t.setText(0, 5, "Account State");
int row = 1;
for (String username : info.keySet()) {
ServiceUserInfo a = info.get(username);
for (int c = 0; c < columns; c++) {
fmt.addStyleName(row, c, "dataCell");
fmt.addStyleName(row, 0, "leftMostCell");
}
t.setWidget(row, 0, new InlineHyperlink(
username, "/x/" + Plugin.get().getName() + "/user/" + username));
t.setText(row, 1, a.name());
t.setText(row, 2, a.email());
t.setText(row, 3, a.created_by());
t.setText(row, 4, a.created_at());
t.setText(row, 5, !a.active() ? "Inactive" : "");
row++;
}
add(t);
}
}
| src/main/java/com/googlesource/gerrit/plugins/serviceuser/client/ServiceUserListScreen.java | // Copyright (C) 2014 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.serviceuser.client;
import com.google.gerrit.plugin.client.Plugin;
import com.google.gerrit.plugin.client.rpc.RestApi;
import com.google.gerrit.plugin.client.screen.Screen;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.InlineHyperlink;
import com.google.gwt.user.client.ui.VerticalPanel;
public class ServiceUserListScreen extends VerticalPanel {
static class Factory implements Screen.EntryPoint {
@Override
public void onLoad(Screen screen) {
screen.setPageTitle("Service Users");
screen.show(new ServiceUserListScreen());
}
}
ServiceUserListScreen() {
setStyleName("serviceuser-panel");
new RestApi("config").id("server").view(Plugin.get().getPluginName(), "serviceusers")
.get(NativeMap.copyKeysIntoChildren("username",
new AsyncCallback<NativeMap<ServiceUserInfo>>() {
@Override
public void onSuccess(NativeMap<ServiceUserInfo> info) {
display(info);
}
@Override
public void onFailure(Throwable caught) {
// never invoked
}
}));
}
private void display(NativeMap<ServiceUserInfo> info) {
int columns = 5;
FlexTable t = new FlexTable();
t.setStyleName("serviceuser-serviceUserTable");
FlexCellFormatter fmt = t.getFlexCellFormatter();
for (int c = 0; c < columns; c++) {
fmt.addStyleName(0, c, "dataHeader");
fmt.addStyleName(0, c, "topMostCell");
}
fmt.addStyleName(0, 0, "leftMostCell");
t.setText(0, 0, "Username");
t.setText(0, 1, "Full Name");
t.setText(0, 2, "Email");
t.setText(0, 3, "Created By");
t.setText(0, 4, "Created At");
int row = 1;
for (String username : info.keySet()) {
ServiceUserInfo a = info.get(username);
for (int c = 0; c < columns; c++) {
fmt.addStyleName(row, c, "dataCell");
fmt.addStyleName(row, 0, "leftMostCell");
}
t.setWidget(row, 0, new InlineHyperlink(
username, "/x/" + Plugin.get().getName() + "/user/" + username));
t.setText(row, 1, a.name());
t.setText(row, 2, a.email());
t.setText(row, 3, a.created_by());
t.setText(row, 4, a.created_at());
row++;
}
add(t);
}
}
| Show account state in service user list
Change-Id: Iaf1547edfbe3de56ce7d9ff82fcd408b1d2258d8
Signed-off-by: Edwin Kempin <[email protected]>
| src/main/java/com/googlesource/gerrit/plugins/serviceuser/client/ServiceUserListScreen.java | Show account state in service user list |
|
Java | apache-2.0 | 241c46936156fe7a97819fb451f4162917bb6ba4 | 0 | eayun/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine | package org.ovirt.engine.ui.uicommonweb.models.storage;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.Model;
@SuppressWarnings("unused")
public class NewEditStorageModelBehavior extends StorageModelBehavior
{
@Override
public void updateItemsAvailability()
{
super.updateItemsAvailability();
StoragePool dataCenter = getModel().getDataCenter().getSelectedItem();
if (dataCenter == null) {
return;
}
// Allow Data storage type corresponding to the selected data-center type + ISO and Export that are NFS only:
for (IStorageModel item : Linq.<IStorageModel> cast(getModel().getItems()))
{
Model model = (Model) item;
if (item.getRole() == StorageDomainType.ISO)
{
AsyncDataProvider.getIsoDomainByDataCenterId(new AsyncQuery(new Object[] { this, item },
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
NewEditStorageModelBehavior behavior = (NewEditStorageModelBehavior) array[0];
IStorageModel storageModelItem = (IStorageModel) array[1];
behavior.postUpdateItemsAvailability(storageModelItem, returnValue == null);
}
}, getHash()), dataCenter.getId());
}
else if (item.getRole() == StorageDomainType.ImportExport)
{
AsyncDataProvider.getExportDomainByDataCenterId(new AsyncQuery(new Object[] { this, item },
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
NewEditStorageModelBehavior behavior = (NewEditStorageModelBehavior) array[0];
IStorageModel storageModelItem = (IStorageModel) array[1];
behavior.postUpdateItemsAvailability(storageModelItem, returnValue == null);
}
}, getHash()), dataCenter.getId());
}
else
{
postUpdateItemsAvailability(item, false);
}
}
}
public void postUpdateItemsAvailability(IStorageModel item, boolean isNoExportOrIsoStorageAttached) {
StoragePool dataCenter = getModel().getDataCenter().getSelectedItem();
checkCanItemBeSelected(item, dataCenter, isNoExportOrIsoStorageAttached);
}
private void checkCanItemBeSelected(final IStorageModel item, StoragePool dataCenter, boolean isNoExportOrIsoStorageAttached) {
boolean isExistingStorage = getModel().getStorage() != null &&
item.getType() == getModel().getStorage().getStorageType();
// If we are in edit mode then the type of the entity edited should appear in the selection
if (isExistingStorage) {
updateItemSelectability(item, true);
return;
}
boolean isExportDomain = item.getRole() == StorageDomainType.ImportExport;
boolean isIsoDomain = item.getRole() == StorageDomainType.ISO;
// Local types should not be selectable for shared data centers and vice versa, only exception is an
// export/import and ISO domains which can be added as NFS
if (!(isExportDomain || isIsoDomain) && isLocalStorage(item) != dataCenter.isLocal()) {
updateItemSelectability(item, false);
return;
}
boolean isNoneDataCenter = dataCenter.getId().equals(StorageModel.UnassignedDataCenterId);
boolean isDataDomain = item.getRole() == StorageDomainType.Data;
// For 'None' data center we allow all data types and no ISO/Export, no reason for further checks
if (isNoneDataCenter) {
updateItemSelectability(item, isDataDomain);
return;
}
boolean canAttachExportDomain = isNoExportOrIsoStorageAttached &&
dataCenter.getStatus() != StoragePoolStatus.Uninitialized;
boolean canAttachIsoDomain = isNoExportOrIsoStorageAttached &&
dataCenter.getStatus() != StoragePoolStatus.Uninitialized;
if ((isExportDomain && canAttachExportDomain) || (isIsoDomain && canAttachIsoDomain)) {
updateItemSelectability(item, true);
return;
}
if (isDataDomain) {
if (isLocalStorage(item)) {
updateItemSelectability(item, true);
return;
}
if (AsyncDataProvider.isMixedStorageDomainsSupported(dataCenter.getcompatibility_version())) {
updateItemSelectability(item, true);
return;
} else {
IdQueryParameters params = new IdQueryParameters(dataCenter.getId());
Frontend.getInstance().runQuery(VdcQueryType.GetStorageTypesInPoolByPoolId, params,
new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object ReturnValue) {
List<StorageType> storageTypes = ((VdcQueryReturnValue) ReturnValue).getReturnValue();
for (StorageType storageType : storageTypes) {
if (storageType.isBlockDomain() != item.getType().isBlockDomain()) {
updateItemSelectability(item, false);
return;
}
}
updateItemSelectability(item, true);
return;
}
}));
return;
}
}
updateItemSelectability(item, false);
}
private void updateItemSelectability(IStorageModel item, boolean isSelectable) {
Model model = (Model) item;
model.setIsSelectable(isSelectable);
onStorageModelUpdated(item);
}
}
| frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/storage/NewEditStorageModelBehavior.java | package org.ovirt.engine.ui.uicommonweb.models.storage;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.Model;
@SuppressWarnings("unused")
public class NewEditStorageModelBehavior extends StorageModelBehavior
{
@Override
public void updateItemsAvailability()
{
super.updateItemsAvailability();
StoragePool dataCenter = getModel().getDataCenter().getSelectedItem();
if (dataCenter == null) {
return;
}
// Allow Data storage type corresponding to the selected data-center type + ISO and Export that are NFS only:
for (IStorageModel item : Linq.<IStorageModel> cast(getModel().getItems()))
{
Model model = (Model) item;
if (item.getRole() == StorageDomainType.ISO)
{
AsyncDataProvider.getIsoDomainByDataCenterId(new AsyncQuery(new Object[] { this, item },
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
NewEditStorageModelBehavior behavior = (NewEditStorageModelBehavior) array[0];
IStorageModel storageModelItem = (IStorageModel) array[1];
behavior.postUpdateItemsAvailability(storageModelItem, returnValue == null);
}
}, getHash()), dataCenter.getId());
}
else if (item.getRole() == StorageDomainType.ImportExport)
{
AsyncDataProvider.getExportDomainByDataCenterId(new AsyncQuery(new Object[] { this, item },
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
NewEditStorageModelBehavior behavior = (NewEditStorageModelBehavior) array[0];
IStorageModel storageModelItem = (IStorageModel) array[1];
behavior.postUpdateItemsAvailability(storageModelItem, returnValue == null);
}
}, getHash()), dataCenter.getId());
}
else
{
postUpdateItemsAvailability(item, false);
}
}
}
public void postUpdateItemsAvailability(IStorageModel item, boolean isNoExportOrIsoStorageAttached) {
StoragePool dataCenter = getModel().getDataCenter().getSelectedItem();
checkCanItemBeSelected(item, dataCenter, isNoExportOrIsoStorageAttached);
}
private void checkCanItemBeSelected(final IStorageModel item, StoragePool dataCenter, boolean isNoExportOrIsoStorageAttached) {
boolean isExistingStorage = getModel().getStorage() != null &&
item.getType() == getModel().getStorage().getStorageType();
// If we are in edit mode then the type of the entity edited should appear in the selection
if (isExistingStorage) {
updateItemSelectability(item, true);
return;
}
// Local types should not be selectable for shared data centers and vice versa
if (isLocalStorage(item) != dataCenter.isLocal()) {
updateItemSelectability(item, false);
return;
}
boolean isNoneDataCenter = dataCenter.getId().equals(StorageModel.UnassignedDataCenterId);
boolean isDataDomain = item.getRole() == StorageDomainType.Data;
// For 'None' data center we allow all data types and no ISO/Export, no reason for further checks
if (isNoneDataCenter) {
updateItemSelectability(item, isDataDomain);
return;
}
boolean isExportDomain = item.getRole() == StorageDomainType.ImportExport;
boolean canAttachExportDomain = isNoExportOrIsoStorageAttached &&
dataCenter.getStatus() != StoragePoolStatus.Uninitialized;
boolean isIsoDomain = item.getRole() == StorageDomainType.ISO;
boolean canAttachIsoDomain = isNoExportOrIsoStorageAttached &&
dataCenter.getStatus() != StoragePoolStatus.Uninitialized;
if ((isExportDomain && canAttachExportDomain) || (isIsoDomain && canAttachIsoDomain)) {
updateItemSelectability(item, true);
return;
}
if (isDataDomain) {
if (isLocalStorage(item)) {
updateItemSelectability(item, true);
return;
}
if (AsyncDataProvider.isMixedStorageDomainsSupported(dataCenter.getcompatibility_version())) {
updateItemSelectability(item, true);
return;
} else {
IdQueryParameters params = new IdQueryParameters(dataCenter.getId());
Frontend.getInstance().runQuery(VdcQueryType.GetStorageTypesInPoolByPoolId, params,
new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object ReturnValue) {
List<StorageType> storageTypes = ((VdcQueryReturnValue) ReturnValue).getReturnValue();
for (StorageType storageType : storageTypes) {
if (storageType.isBlockDomain() != item.getType().isBlockDomain()) {
updateItemSelectability(item, false);
return;
}
}
updateItemSelectability(item, true);
return;
}
}));
return;
}
}
updateItemSelectability(item, false);
}
private void updateItemSelectability(IStorageModel item, boolean isSelectable) {
Model model = (Model) item;
model.setIsSelectable(isSelectable);
onStorageModelUpdated(item);
}
}
| webadmin: Allow adding of NFS export/ISO domains to a local DC
Change-Id: I7122566506fe4b146fa8e3035c5656303a6bd9ae
Bug-Url: https://bugzilla.redhat.com/1097837
Signed-off-by: Tal Nisan <[email protected]>
| frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/storage/NewEditStorageModelBehavior.java | webadmin: Allow adding of NFS export/ISO domains to a local DC |
|
Java | apache-2.0 | 957bc57d40e37376c35ded7e9c38fb94717d3b14 | 0 | MatthewTamlin/Spyglass | package com.matthewtamlin.spyglass.processors.code_generation;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import static javax.lang.model.element.Modifier.ABSTRACT;
import static javax.lang.model.element.Modifier.PUBLIC;
public final class CallerDef {
public static final String PACKAGE = "com.matthewtamlin.spyglass.processors.code_generation";
public static final String INTERFACE_NAME = "Caller";
public static final String METHOD_NAME = "call";
public static JavaFile getJavaFile() {
final TypeVariableName targetType = TypeVariableName.get("T");
final MethodSpec methodSpec = MethodSpec
.methodBuilder(METHOD_NAME)
.addModifiers(PUBLIC, ABSTRACT)
.returns(void.class)
.addParameter(targetType, "target")
.addParameter(AndroidClassNames.CONTEXT, "context")
.addParameter(AndroidClassNames.TYPED_ARRAY, "attributes")
.build();
final TypeSpec interfaceSpec = TypeSpec
.interfaceBuilder(INTERFACE_NAME)
.addModifiers(PUBLIC, ABSTRACT)
.addTypeVariable(targetType)
.addMethod(methodSpec)
.build();
return JavaFile
.builder(PACKAGE, interfaceSpec)
.addFileComment("Spyglass auto-generated file. Do not modify!")
.build();
}
private CallerDef() {
throw new RuntimeException("Contract class. Do not instantiate.");
}
} | processor/src/main/java/com/matthewtamlin/spyglass/processors/code_generation/CallerDef.java | package com.matthewtamlin.spyglass.processors.code_generation;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import static javax.lang.model.element.Modifier.ABSTRACT;
import static javax.lang.model.element.Modifier.PUBLIC;
public final class CallerDef {
public static final String PACKAGE = "com.matthewtamlin.spyglass.processors.code_generation";
public static final String INTERFACE_NAME = "Caller";
public static final String METHOD_NAME = "callMethod";
public static JavaFile getJavaFile() {
final TypeVariableName targetType = TypeVariableName.get("T");
final MethodSpec methodSpec = MethodSpec
.methodBuilder(METHOD_NAME)
.addModifiers(PUBLIC, ABSTRACT)
.returns(void.class)
.addParameter(targetType, "target")
.addParameter(AndroidClassNames.CONTEXT, "context")
.addParameter(AndroidClassNames.TYPED_ARRAY, "attributes")
.build();
final TypeSpec interfaceSpec = TypeSpec
.interfaceBuilder(INTERFACE_NAME)
.addModifiers(PUBLIC, ABSTRACT)
.addTypeVariable(targetType)
.addMethod(methodSpec)
.build();
return JavaFile
.builder(PACKAGE, interfaceSpec)
.addFileComment("Spyglass auto-generated file. Do not modify!")
.build();
}
private CallerDef() {
throw new RuntimeException("Contract class. Do not instantiate.");
}
} | Changed method name definition
| processor/src/main/java/com/matthewtamlin/spyglass/processors/code_generation/CallerDef.java | Changed method name definition |
|
Java | apache-2.0 | 5c7a3ab7332feb4ef471be649e9739deb588f00a | 0 | advantageous/ddp-client-java,advantageous/ddp-client-java | /*
* Copyright (C) 2014. Geoffrey Chandler.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.meteor.sample;
import com.google.inject.Guice;
import com.google.inject.Injector;
import javafx.application.Application;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.meteor.ddp.DDPMessageEndpoint;
import org.meteor.ddp.ErrorMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.IOException;
public class SampleApplication extends Application {
private static final Logger LOGGER = LoggerFactory.getLogger(SampleApplication.class);
@Inject
private DDPMessageEndpoint endpoint;
@Inject
private MainViewController mainController;
{
final Injector injector = Guice.createInjector(new SampleApplicationModule());
final FXMLLoader loader = new FXMLLoader(getClass().getResource("MainView.fxml"));
loader.setControllerFactory(injector::getInstance);
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
injector.injectMembers(this);
endpoint.registerHandler(ErrorMessage.class, message -> LOGGER.error(message.getReason()));
}
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
MeteorService thread = new MeteorService();
thread.start();
Parent root = mainController.getRoot();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
class MeteorService extends Service {
@Override
protected Task createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
endpoint.connect("ws://localhost:3000/websocket");
endpoint.await();
LOGGER.warn("disconected from endpoint");
return null;
}
};
}
}
}
| examples/java-fx/src/main/java/org/meteor/sample/SampleApplication.java | /*
* Copyright (C) 2014. Geoffrey Chandler.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.meteor.sample;
import com.google.inject.Guice;
import com.google.inject.Injector;
import javafx.application.Application;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.meteor.ddp.DDPMessageEndpoint;
import org.meteor.ddp.ErrorMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.IOException;
public class SampleApplication extends Application {
private static final Logger LOGGER = LoggerFactory.getLogger(SampleApplication.class);
@Inject
private DDPMessageEndpoint endpoint;
@Inject
private MainViewController mainController;
{
final Injector injector = Guice.createInjector(new SampleApplicationModule());
final FXMLLoader loader = new FXMLLoader(getClass().getResource("MainView.fxml"));
loader.setControllerFactory(injector::getInstance);
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
injector.injectMembers(this);
endpoint.registerHandler(ErrorMessage.class, message -> LOGGER.error("error: " + message.getReason()));
}
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
MeteorService thread = new MeteorService();
thread.start();
Parent root = mainController.getRoot();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
class MeteorService extends Service {
@Override
protected Task createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
endpoint.connect("ws://localhost:3000/websocket");
endpoint.await();
LOGGER.warn("disconected from endpoint");
return null;
}
};
}
}
}
| cleaner error message
| examples/java-fx/src/main/java/org/meteor/sample/SampleApplication.java | cleaner error message |
|
Java | apache-2.0 | 1903c76bfd0926dab96613d695b43f34ef6899e7 | 0 | alexbbb/android-upload-service,NativeScript/android-upload-service,NativeScript/android-upload-service,gotev/android-upload-service,alexbbb/android-upload-service,gotev/android-upload-service,NativeScript/android-upload-service | package net.gotev.uploadservice;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import net.gotev.uploadservice.http.HttpStack;
import net.gotev.uploadservice.http.impl.OkHttpStack;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Service to upload files in background using HTTP POST with notification center progress
* display.
*
* @author gotev (Aleksandar Gotev)
* @author eliasnaur
* @author cankov
* @author mabdurrahman
*/
public final class UploadService extends Service {
private static final String TAG = UploadService.class.getSimpleName();
// configurable values
/**
* Sets how many threads to use to handle concurrent uploads.
*/
public static int UPLOAD_POOL_SIZE = Runtime.getRuntime().availableProcessors();
/**
* When the number of threads is greater than UPLOAD_POOL_SIZE, this is the maximum time that
* excess idle threads will wait for new tasks before terminating.
*/
public static int KEEP_ALIVE_TIME_IN_SECONDS = 1;
/**
* If set to true, the service will go in foreground mode when doing uploads,
* lowering the probability of being killed by the system on low memory.
* This setting is used only when your uploads have a notification configuration.
* It's not possible to run in foreground without notifications, as per Android policy
* constraints, so if you set this to true, but you do upload tasks without a
* notification configuration, the service will simply run in background mode.
*/
public static boolean EXECUTE_IN_FOREGROUND = true;
/**
* Sets the namespace used to broadcast events. Set this to your app namespace to avoid
* conflicts and unexpected behaviours.
*/
public static String NAMESPACE = "net.gotev";
/**
* Sets the HTTP Stack to use to perform HTTP based upload requests.
* By default {@link OkHttpStack} implementation is used.
*/
public static HttpStack HTTP_STACK = new OkHttpStack();
/**
* Buffer size in bytes used for data transfer by the upload tasks.
*/
public static int BUFFER_SIZE = 4096;
/**
* Sets the time to wait in milliseconds before the next attempt when an upload fails
* for the first time. From the second time onwards, this value will be multiplied by
* {@link UploadService#BACKOFF_MULTIPLIER} to get the time to wait before the next attempt.
*/
public static int INITIAL_RETRY_WAIT_TIME = 1000;
/**
* Sets the backoff timer multiplier. By default is set to 10, so every time that an upload
* fails, the time to wait between retries will be multiplied by 10.
* E.g. if the first time the wait time is 1s, the second time it will be 10s and the third
* time it will be 100s.
*/
public static int BACKOFF_MULTIPLIER = 10;
/**
* Sets the maximum time to wait in milliseconds between two upload attempts.
* This is useful because every time an upload fails, the wait time gets multiplied by
* {@link UploadService#BACKOFF_MULTIPLIER} and it's not convenient that the value grows
* indefinitely.
*/
public static int MAX_RETRY_WAIT_TIME = 10 * 60 * 1000;
// end configurable values
protected static final int UPLOAD_NOTIFICATION_BASE_ID = 1234; // Something unique
/**
* The minimum interval between progress reports in milliseconds.
* If the upload Tasks report more frequently, we will throttle notifications.
* We aim for 6 updates per second.
*/
protected static final long PROGRESS_REPORT_INTERVAL = 166;
// constants used in the intent which starts this service
private static final String ACTION_UPLOAD_SUFFIX = ".uploadservice.action.upload";
protected static final String PARAM_TASK_PARAMETERS = "taskParameters";
protected static final String PARAM_TASK_CLASS = "taskClass";
// constants used in broadcast intents
private static final String BROADCAST_ACTION_SUFFIX = ".uploadservice.broadcast.status";
protected static final String PARAM_BROADCAST_DATA = "broadcastData";
// internal variables
private PowerManager.WakeLock wakeLock;
private int notificationIncrementalId = 0;
private static final Map<String, UploadTask> uploadTasksMap = new ConcurrentHashMap<>();
private static final Map<String, UploadStatusDelegate> uploadDelegates = new ConcurrentHashMap<>();
private final BlockingQueue<Runnable> uploadTasksQueue = new LinkedBlockingQueue<>();
private static volatile String foregroundUploadId = null;
private ThreadPoolExecutor uploadThreadPool;
protected static String getActionUpload() {
return NAMESPACE + ACTION_UPLOAD_SUFFIX;
}
protected static String getActionBroadcast() {
return NAMESPACE + BROADCAST_ACTION_SUFFIX;
}
/**
* Stops the upload task with the given uploadId.
* @param uploadId The unique upload id
*/
public static synchronized void stopUpload(final String uploadId) {
UploadTask removedTask = uploadTasksMap.get(uploadId);
if (removedTask != null) {
removedTask.cancel();
}
}
/**
* Gets the list of the currently active upload tasks.
* @return list of uploadIDs or an empty list if no tasks are currently running
*/
public static synchronized List<String> getTaskList() {
List<String> tasks;
if (uploadTasksMap.isEmpty()) {
tasks = new ArrayList<>(1);
} else {
tasks = new ArrayList<>(uploadTasksMap.size());
tasks.addAll(uploadTasksMap.keySet());
}
return tasks;
}
/**
* Stop all the active uploads.
*/
public static synchronized void stopAllUploads() {
if (uploadTasksMap.isEmpty()) {
return;
}
// using iterator instead for each loop, because it's faster on Android
Iterator<String> iterator = uploadTasksMap.keySet().iterator();
while (iterator.hasNext()) {
UploadTask taskToCancel = uploadTasksMap.get(iterator.next());
taskToCancel.cancel();
}
}
@Override
public void onCreate() {
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wakeLock.setReferenceCounted(false);
if (!wakeLock.isHeld())
wakeLock.acquire();
if (UPLOAD_POOL_SIZE <= 0) {
UPLOAD_POOL_SIZE = Runtime.getRuntime().availableProcessors();
}
// Creates a thread pool manager
uploadThreadPool = new ThreadPoolExecutor(
UPLOAD_POOL_SIZE, // Initial pool size
UPLOAD_POOL_SIZE, // Max pool size
KEEP_ALIVE_TIME_IN_SECONDS,
TimeUnit.SECONDS,
uploadTasksQueue);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null || !getActionUpload().equals(intent.getAction())) {
return shutdownIfThereArentAnyActiveTasks();
}
Logger.info(TAG, String.format(Locale.getDefault(), "Starting service with namespace: %s, " +
"upload pool size: %d, %ds idle thread keep alive time. Foreground execution is %s",
NAMESPACE, UPLOAD_POOL_SIZE, KEEP_ALIVE_TIME_IN_SECONDS,
(EXECUTE_IN_FOREGROUND ? "enabled" : "disabled")));
UploadTask currentTask = getTask(intent);
if (currentTask == null) {
return shutdownIfThereArentAnyActiveTasks();
}
if (uploadTasksMap.containsKey(currentTask.params.getId())) {
Logger.error(TAG, "Preventing upload with id: " + currentTask.params.getId()
+ " to be uploaded twice! Please check your code and fix it!");
return shutdownIfThereArentAnyActiveTasks();
}
// increment by 2 because the notificationIncrementalId + 1 is used internally
// in each UploadTask. Check its sources for more info about this.
notificationIncrementalId += 2;
currentTask.setLastProgressNotificationTime(0)
.setNotificationId(UPLOAD_NOTIFICATION_BASE_ID + notificationIncrementalId);
uploadTasksMap.put(currentTask.params.getId(), currentTask);
uploadThreadPool.execute(currentTask);
return START_STICKY;
}
private int shutdownIfThereArentAnyActiveTasks() {
if (uploadTasksMap.isEmpty()) {
stopSelf();
return START_NOT_STICKY;
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopAllUploads();
uploadThreadPool.shutdown();
if (EXECUTE_IN_FOREGROUND) {
Logger.debug(TAG, "Stopping foreground execution");
stopForeground(true);
}
if (wakeLock.isHeld())
wakeLock.release();
uploadTasksMap.clear();
uploadDelegates.clear();
Logger.debug(TAG, "UploadService destroyed");
}
/**
* Creates a new task instance based on the requested task class in the intent.
* @param intent intent passed to the service
* @return task instance or null if the task class is not supported or invalid
*/
UploadTask getTask(Intent intent) {
String taskClass = intent.getStringExtra(PARAM_TASK_CLASS);
if (taskClass == null) {
return null;
}
UploadTask uploadTask = null;
try {
Class<?> task = Class.forName(taskClass);
if (UploadTask.class.isAssignableFrom(task)) {
uploadTask = UploadTask.class.cast(task.newInstance());
uploadTask.init(this, intent);
} else {
Logger.error(TAG, taskClass + " does not extend UploadTask!");
}
Logger.debug(TAG, "Successfully created new task with class: " + taskClass);
} catch (Exception exc) {
Logger.error(TAG, "Error while instantiating new task", exc);
}
return uploadTask;
}
/**
* Check if the task is currently the one shown in the foreground notification.
* @param uploadId ID of the upload
* @return true if the current upload task holds the foreground notification, otherwise false
*/
protected synchronized boolean holdForegroundNotification(String uploadId, Notification notification) {
if (!EXECUTE_IN_FOREGROUND) return false;
if (foregroundUploadId == null) {
foregroundUploadId = uploadId;
Logger.debug(TAG, uploadId + " now holds the foreground notification");
}
if (uploadId.equals(foregroundUploadId)) {
startForeground(UPLOAD_NOTIFICATION_BASE_ID, notification);
return true;
}
return false;
}
/**
* Called by each task when it is completed (either successfully, with an error or due to
* user cancellation).
* @param uploadId the uploadID of the finished task
*/
protected synchronized void taskCompleted(String uploadId) {
UploadTask task = uploadTasksMap.remove(uploadId);
uploadDelegates.remove(uploadId);
// un-hold foreground upload ID if it's been hold
if (EXECUTE_IN_FOREGROUND && task != null && task.params.getId().equals(foregroundUploadId)) {
Logger.debug(TAG, uploadId + " now un-holded the foreground notification");
foregroundUploadId = null;
}
// when all the upload tasks are completed, release the wake lock and shut down the service
if (uploadTasksMap.isEmpty()) {
Logger.debug(TAG, "All tasks finished. UploadService is about to shutdown...");
stopSelf();
}
}
/**
* Sets the delegate which will receive the events for the given upload request.
* Those events will not be sent in broadcast, but only to the delegate.
* @param uploadId uploadID of the upload request
* @param delegate the delegate instance
*/
protected static void setUploadStatusDelegate(String uploadId, UploadStatusDelegate delegate) {
if (delegate == null)
return;
uploadDelegates.put(uploadId, delegate);
}
/**
* Gets the delegate for an upload request.
* @param uploadId uploadID of the upload request
* @return {@link UploadStatusDelegate} or null if no delegate has been set for the given
* uploadId
*/
protected static UploadStatusDelegate getUploadStatusDelegate(String uploadId) {
return uploadDelegates.get(uploadId);
}
}
| uploadservice/src/main/java/net/gotev/uploadservice/UploadService.java | package net.gotev.uploadservice;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import net.gotev.uploadservice.http.HttpStack;
import net.gotev.uploadservice.http.impl.OkHttpStack;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Service to upload files in background using HTTP POST with notification center progress
* display.
*
* @author gotev (Aleksandar Gotev)
* @author eliasnaur
* @author cankov
* @author mabdurrahman
*/
public final class UploadService extends Service {
private static final String TAG = UploadService.class.getSimpleName();
// configurable values
/**
* Sets how many threads to use to handle concurrent uploads.
*/
public static int UPLOAD_POOL_SIZE = Runtime.getRuntime().availableProcessors();
/**
* When the number of threads is greater than UPLOAD_POOL_SIZE, this is the maximum time that
* excess idle threads will wait for new tasks before terminating.
*/
public static int KEEP_ALIVE_TIME_IN_SECONDS = 1;
/**
* If set to true, the service will go in foreground mode when doing uploads,
* lowering the probability of being killed by the system on low memory.
* This setting is used only when your uploads have a notification configuration.
* It's not possible to run in foreground without notifications, as per Android policy
* constraints, so if you set this to true, but you do upload tasks without a
* notification configuration, the service will simply run in background mode.
*/
public static boolean EXECUTE_IN_FOREGROUND = true;
/**
* Sets the namespace used to broadcast events. Set this to your app namespace to avoid
* conflicts and unexpected behaviours.
*/
public static String NAMESPACE = "net.gotev";
/**
* Sets the HTTP Stack to use to perform HTTP based upload requests.
* By default {@link OkHttpStack} implementation is used.
*/
public static HttpStack HTTP_STACK = new OkHttpStack();
/**
* Buffer size in bytes used for data transfer by the upload tasks.
*/
public static int BUFFER_SIZE = 4096;
/**
* Sets the time to wait in milliseconds before the next attempt when an upload fails
* for the first time. From the second time onwards, this value will be multiplied by
* {@link UploadService#BACKOFF_MULTIPLIER} to get the time to wait before the next attempt.
*/
public static int INITIAL_RETRY_WAIT_TIME = 1000;
/**
* Sets the backoff timer multiplier. By default is set to 10, so every time that an upload
* fails, the time to wait between retries will be multiplied by 10.
* E.g. if the first time the wait time is 1s, the second time it will be 10s and the third
* time it will be 100s.
*/
public static int BACKOFF_MULTIPLIER = 10;
/**
* Sets the maximum time to wait in milliseconds between two upload attempts.
* This is useful because every time an upload fails, the wait time gets multiplied by
* {@link UploadService#BACKOFF_MULTIPLIER} and it's not convenient that the value grows
* indefinitely.
*/
public static int MAX_RETRY_WAIT_TIME = 10 * 60 * 1000;
// end configurable values
protected static final int UPLOAD_NOTIFICATION_BASE_ID = 1234; // Something unique
/**
* The minimum interval between progress reports in milliseconds.
* If the upload Tasks report more frequently, we will throttle notifications.
* We aim for 6 updates per second.
*/
protected static final long PROGRESS_REPORT_INTERVAL = 166;
// constants used in the intent which starts this service
private static final String ACTION_UPLOAD_SUFFIX = ".uploadservice.action.upload";
protected static final String PARAM_TASK_PARAMETERS = "taskParameters";
protected static final String PARAM_TASK_CLASS = "taskClass";
// constants used in broadcast intents
private static final String BROADCAST_ACTION_SUFFIX = ".uploadservice.broadcast.status";
protected static final String PARAM_BROADCAST_DATA = "broadcastData";
// internal variables
private PowerManager.WakeLock wakeLock;
private int notificationIncrementalId = 0;
private static final Map<String, UploadTask> uploadTasksMap = new ConcurrentHashMap<>();
private static final Map<String, UploadStatusDelegate> uploadDelegates = new ConcurrentHashMap<>();
private final BlockingQueue<Runnable> uploadTasksQueue = new LinkedBlockingQueue<>();
private static volatile String foregroundUploadId = null;
private ThreadPoolExecutor uploadThreadPool;
protected static String getActionUpload() {
return NAMESPACE + ACTION_UPLOAD_SUFFIX;
}
protected static String getActionBroadcast() {
return NAMESPACE + BROADCAST_ACTION_SUFFIX;
}
/**
* Stops the upload task with the given uploadId.
* @param uploadId The unique upload id
*/
public static synchronized void stopUpload(final String uploadId) {
UploadTask removedTask = uploadTasksMap.get(uploadId);
if (removedTask != null) {
removedTask.cancel();
}
}
/**
* Gets the list of the currently active upload tasks.
* @return list of uploadIDs or an empty list if no tasks are currently running
*/
public static synchronized List<String> getTaskList() {
List<String> tasks;
if (uploadTasksMap.isEmpty()) {
tasks = new ArrayList<>(1);
} else {
tasks = new ArrayList<>(uploadTasksMap.size());
tasks.addAll(uploadTasksMap.keySet());
}
return tasks;
}
/**
* Stop all the active uploads.
*/
public static synchronized void stopAllUploads() {
if (uploadTasksMap.isEmpty()) {
return;
}
// using iterator instead for each loop, because it's faster on Android
Iterator<String> iterator = uploadTasksMap.keySet().iterator();
while (iterator.hasNext()) {
UploadTask taskToCancel = uploadTasksMap.get(iterator.next());
taskToCancel.cancel();
}
}
@Override
public void onCreate() {
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wakeLock.setReferenceCounted(false);
if (!wakeLock.isHeld())
wakeLock.acquire();
if (UPLOAD_POOL_SIZE <= 0) {
UPLOAD_POOL_SIZE = Runtime.getRuntime().availableProcessors();
}
// Creates a thread pool manager
uploadThreadPool = new ThreadPoolExecutor(
UPLOAD_POOL_SIZE, // Initial pool size
UPLOAD_POOL_SIZE, // Max pool size
KEEP_ALIVE_TIME_IN_SECONDS,
TimeUnit.SECONDS,
uploadTasksQueue);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null || !getActionUpload().equals(intent.getAction())) {
return shutdownIfThereArentAnyActiveTasks();
}
Logger.info(TAG, String.format(Locale.getDefault(), "Starting service with namespace: %s, " +
"upload pool size: %d, %ds idle thread keep alive time. Foreground execution is %s",
NAMESPACE, UPLOAD_POOL_SIZE, KEEP_ALIVE_TIME_IN_SECONDS,
(EXECUTE_IN_FOREGROUND ? "enabled" : "disabled")));
UploadTask currentTask = getTask(intent);
if (currentTask == null) {
return shutdownIfThereArentAnyActiveTasks();
}
// increment by 2 because the notificationIncrementalId + 1 is used internally
// in each UploadTask. Check its sources for more info about this.
notificationIncrementalId += 2;
currentTask.setLastProgressNotificationTime(0)
.setNotificationId(UPLOAD_NOTIFICATION_BASE_ID + notificationIncrementalId);
uploadTasksMap.put(currentTask.params.getId(), currentTask);
uploadThreadPool.execute(currentTask);
return START_STICKY;
}
private int shutdownIfThereArentAnyActiveTasks() {
if (uploadTasksMap.isEmpty()) {
stopSelf();
return START_NOT_STICKY;
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopAllUploads();
uploadThreadPool.shutdown();
if (EXECUTE_IN_FOREGROUND) {
Logger.debug(TAG, "Stopping foreground execution");
stopForeground(true);
}
if (wakeLock.isHeld())
wakeLock.release();
uploadTasksMap.clear();
uploadDelegates.clear();
Logger.debug(TAG, "UploadService destroyed");
}
/**
* Creates a new task instance based on the requested task class in the intent.
* @param intent intent passed to the service
* @return task instance or null if the task class is not supported or invalid
*/
UploadTask getTask(Intent intent) {
String taskClass = intent.getStringExtra(PARAM_TASK_CLASS);
if (taskClass == null) {
return null;
}
UploadTask uploadTask = null;
try {
Class<?> task = Class.forName(taskClass);
if (UploadTask.class.isAssignableFrom(task)) {
uploadTask = UploadTask.class.cast(task.newInstance());
uploadTask.init(this, intent);
} else {
Logger.error(TAG, taskClass + " does not extend UploadTask!");
}
Logger.debug(TAG, "Successfully created new task with class: " + taskClass);
} catch (Exception exc) {
Logger.error(TAG, "Error while instantiating new task", exc);
}
return uploadTask;
}
/**
* Check if the task is currently the one shown in the foreground notification.
* @param uploadId ID of the upload
* @return true if the current upload task holds the foreground notification, otherwise false
*/
protected synchronized boolean holdForegroundNotification(String uploadId, Notification notification) {
if (!EXECUTE_IN_FOREGROUND) return false;
if (foregroundUploadId == null) {
foregroundUploadId = uploadId;
Logger.debug(TAG, uploadId + " now holds the foreground notification");
}
if (uploadId.equals(foregroundUploadId)) {
startForeground(UPLOAD_NOTIFICATION_BASE_ID, notification);
return true;
}
return false;
}
/**
* Called by each task when it is completed (either successfully, with an error or due to
* user cancellation).
* @param uploadId the uploadID of the finished task
*/
protected synchronized void taskCompleted(String uploadId) {
UploadTask task = uploadTasksMap.remove(uploadId);
uploadDelegates.remove(uploadId);
// un-hold foreground upload ID if it's been hold
if (EXECUTE_IN_FOREGROUND && task != null && task.params.getId().equals(foregroundUploadId)) {
Logger.debug(TAG, uploadId + " now un-holded the foreground notification");
foregroundUploadId = null;
}
// when all the upload tasks are completed, release the wake lock and shut down the service
if (uploadTasksMap.isEmpty()) {
Logger.debug(TAG, "All tasks finished. UploadService is about to shutdown...");
stopSelf();
}
}
/**
* Sets the delegate which will receive the events for the given upload request.
* Those events will not be sent in broadcast, but only to the delegate.
* @param uploadId uploadID of the upload request
* @param delegate the delegate instance
*/
protected static void setUploadStatusDelegate(String uploadId, UploadStatusDelegate delegate) {
if (delegate == null)
return;
uploadDelegates.put(uploadId, delegate);
}
/**
* Gets the delegate for an upload request.
* @param uploadId uploadID of the upload request
* @return {@link UploadStatusDelegate} or null if no delegate has been set for the given
* uploadId
*/
protected static UploadStatusDelegate getUploadStatusDelegate(String uploadId) {
return uploadDelegates.get(uploadId);
}
}
| #213 prevent duplicate uploads
| uploadservice/src/main/java/net/gotev/uploadservice/UploadService.java | #213 prevent duplicate uploads |
|
Java | apache-2.0 | 8a5b828d83e7012a2aa69296cb4a770e5ac301d9 | 0 | smalldatalab/omh-dsu,smalldatalab/omh-dsu,smalldatalab/omh-dsu,smalldatalab/omh-dsu | /*
* Copyright 2014 Open mHealth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openmhealth.dsu.configuration;
import io.smalldata.ohmageomh.dsu.configuration.AuthenticationProcessingFilterEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.social.security.SpringSocialConfigurer;
/**
* A Spring Security configuration that provides an authentication manager for user accounts and disables
* Spring Boot's security configuration.
*
* @author Emerson Farrugia
* @author Jared Sieling
*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
@Bean(name = "authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/css/**", "/images/**", "/js/**", "/fonts/**", "/favicon.ico");
}
/**
*
* @return a signin successHandler that redirect to the originally requested page
*/
@Bean
public SavedRequestAwareAuthenticationSuccessHandler successHandler() {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setUseReferer(true);
return successHandler;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
// redirect all unauthenticated request to google sign-in
.loginPage("/signin")
.successHandler(successHandler())
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
.and()
// permit unauthenticated access to favicon, signin page and auth pages for different social services
.authorizeRequests()
.antMatchers(
"/signin",
"/auth/**", // web social signin endpoints
"/social-signin/**", // mobile social signin endpoints
"/google-signin**" // mobile google social signin endpoint (FIXME: deprecated)
).permitAll()
// oauth token endpoints
// (oauth/authorize should only be accessed by users who have signin, so is excluded from here)
.antMatchers("/oauth/token", "/oauth/check_token")
.permitAll()
.antMatchers("/users")
.hasIpAddress("127.0.0.1")// only allow users to be created from local request
.antMatchers("/**")
.authenticated()
// enable cookie
.and()
.rememberMe()
// apply Spring Social config that add Spring Social to be an AuthenticationProvider
.and()
.apply(new SpringSocialConfigurer())
.and()
// Disable CSRF protection FIXME: apply stricter access control to auth pages and oauth/authorize
.csrf().disable()
// use a custom authentication entry point to preserve query parameter
.exceptionHandling().authenticationEntryPoint(new AuthenticationProcessingFilterEntryPoint("/signin"));
}
}
| authorization-server/src/main/java/org/openmhealth/dsu/configuration/SecurityConfiguration.java | /*
* Copyright 2014 Open mHealth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openmhealth.dsu.configuration;
import io.smalldata.ohmageomh.dsu.configuration.AuthenticationProcessingFilterEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.social.security.SpringSocialConfigurer;
/**
* A Spring Security configuration that provides an authentication manager for user accounts and disables
* Spring Boot's security configuration.
*
* @author Emerson Farrugia
* @author Jared Sieling
*/
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
@Bean(name = "authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/css/**", "/images/**", "/js/**", "/fonts/**", "/favicon.ico");
}
/**
*
* @return a signin successHandler that redirect to the originally requested page
*/
@Bean
public SavedRequestAwareAuthenticationSuccessHandler successHandler() {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setUseReferer(true);
return successHandler;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
// redirect all unauthenticated request to google sign-in
.loginPage("/signin")
.successHandler(successHandler())
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
.and()
// permit unauthenticated access to favicon, signin page and auth pages for different social services
.authorizeRequests()
.antMatchers(
"/signin",
"/auth/**", // web social signin endpoints
"/social-signin/**", // mobile social signin endpoints
"/google-signin**" // mobile google social signin endpoint (FIXME: deprecated)
).permitAll()
// oauth token endpoints
// (oauth/authorize should only be accessed by users who have signin, so is excluded from here)
.antMatchers("/oauth/token", "/oauth/check_token")
.permitAll()
.antMatchers("/internal/**")
.hasIpAddress("127.0.0.1")// internal endpoints.
.antMatchers("/**")
.authenticated()
// enable cookie
.and()
.rememberMe()
// apply Spring Social config that add Spring Social to be an AuthenticationProvider
.and()
.apply(new SpringSocialConfigurer())
.and()
// Disable CSRF protection FIXME: apply stricter access control to auth pages and oauth/authorize
.csrf().disable()
// use a custom authentication entry point to preserve query parameter
.exceptionHandling().authenticationEntryPoint(new AuthenticationProcessingFilterEntryPoint("/signin"));
}
}
| Allow users to be created locally at new endpoint.
| authorization-server/src/main/java/org/openmhealth/dsu/configuration/SecurityConfiguration.java | Allow users to be created locally at new endpoint. |
|
Java | apache-2.0 | debb2ddf1d8adea094d240ebb7b85568aca6068f | 0 | gchq/Gaffer,flitte/Gaffer,flitte/Gaffer,flitte/Gaffer,GovernmentCommunicationsHeadquarters/Gaffer,gchq/Gaffer,GovernmentCommunicationsHeadquarters/Gaffer,gchq/Gaffer,flitte/Gaffer,gchq/Gaffer,GovernmentCommunicationsHeadquarters/Gaffer,GovernmentCommunicationsHeadquarters/Gaffer | /*
* Copyright 2016 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gaffer.accumulostore.retriever;
import gaffer.accumulostore.AccumuloStore;
import gaffer.accumulostore.key.exception.AccumuloElementConversionException;
import gaffer.accumulostore.key.exception.RangeFactoryException;
import gaffer.accumulostore.utils.CloseableIterator;
import gaffer.data.element.Element;
import gaffer.operation.GetOperation;
import gaffer.store.StoreException;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public abstract class AccumuloItemRetriever<OP_TYPE extends GetOperation<? extends SEED_TYPE, ?>, SEED_TYPE>
extends AccumuloRetriever<OP_TYPE> {
private static final Logger LOGGER = LoggerFactory.getLogger(AccumuloItemRetriever.class);
private final Iterable<? extends SEED_TYPE> ids;
protected AccumuloItemRetriever(final AccumuloStore store, final OP_TYPE operation,
final IteratorSetting... iteratorSettings) throws StoreException {
super(store, operation, iteratorSettings);
this.ids = operation.getSeeds();
}
@Override
public Iterator<Element> iterator() {
Iterator<? extends SEED_TYPE> idIterator = ids.iterator();
if (!idIterator.hasNext()) {
return Collections.emptyIterator();
}
try {
iterator = new ElementIterator(idIterator);
} catch (final RetrieverException e) {
LOGGER.error(e.getMessage() + " returning empty iterator", e);
return Collections.emptyIterator();
}
return iterator;
}
protected abstract void addToRanges(final SEED_TYPE seed, final Set<Range> ranges) throws RangeFactoryException;
protected class ElementIterator implements CloseableIterator<Element> {
private final Iterator<? extends SEED_TYPE> idsIterator;
private int count;
private BatchScanner scanner;
private Iterator<Map.Entry<Key, Value>> scannerIterator;
protected ElementIterator(final Iterator<? extends SEED_TYPE> idIterator) throws RetrieverException {
idsIterator = idIterator;
count = 0;
final Set<Range> ranges = new HashSet<>();
while (idsIterator.hasNext() && count < store.getProperties().getMaxEntriesForBatchScanner()) {
count++;
try {
addToRanges(idsIterator.next(), ranges);
} catch (final RangeFactoryException e) {
LOGGER.error("Failed to create a range from given seed pair", e);
}
}
// Create BatchScanner, appropriately configured (i.e. ranges,
// iterators, etc).
try {
scanner = getScanner(ranges);
} catch (TableNotFoundException | StoreException e) {
throw new RetrieverException(e);
}
scannerIterator = scanner.iterator();
}
@Override
public boolean hasNext() {
// If current scanner has next then return true.
if (scannerIterator.hasNext()) {
return true;
}
// If current scanner is spent then go back to the iterator
// through the provided entities, and see if there are more.
// If so create the next scanner, if there are no more entities
// then return false.
while (idsIterator.hasNext() && !scannerIterator.hasNext()) {
count = 0;
final Set<Range> ranges = new HashSet<>();
while (idsIterator.hasNext() && count < store.getProperties().getMaxEntriesForBatchScanner()) {
count++;
try {
addToRanges(idsIterator.next(), ranges);
} catch (final RangeFactoryException e) {
LOGGER.error("Failed to create a range from given seed", e);
}
}
scanner.close();
try {
scanner = getScanner(ranges);
} catch (TableNotFoundException | StoreException e) {
LOGGER.error(e.getMessage() + " returning iterator doesn't have any more elements", e);
return false;
}
scannerIterator = scanner.iterator();
}
if (!scannerIterator.hasNext()) {
scanner.close();
return false;
}
return true;
}
@Override
public Element next() {
final Map.Entry<Key, Value> entry = scannerIterator.next();
try {
final Element elm = elementConverter.getFullElement(entry.getKey(), entry.getValue(),
operation.getOptions());
doTransformation(elm);
return elm;
} catch (final AccumuloElementConversionException e) {
LOGGER.error("Failed to re-create an element from a key value entry set returning next element as null",
e);
return null;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("Unable to remove elements from this iterator");
}
@Override
public void close() {
if (scanner != null) {
scanner.close();
}
}
}
}
| accumulo-store/src/main/java/gaffer/accumulostore/retriever/AccumuloItemRetriever.java | /*
* Copyright 2016 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gaffer.accumulostore.retriever;
import gaffer.accumulostore.AccumuloStore;
import gaffer.accumulostore.key.exception.AccumuloElementConversionException;
import gaffer.accumulostore.key.exception.RangeFactoryException;
import gaffer.accumulostore.utils.CloseableIterator;
import gaffer.data.element.Element;
import gaffer.operation.GetOperation;
import gaffer.store.StoreException;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public abstract class AccumuloItemRetriever<OP_TYPE extends GetOperation<? extends SEED_TYPE, ?>, SEED_TYPE>
extends AccumuloRetriever<OP_TYPE> {
private static final Logger LOGGER = LoggerFactory.getLogger(AccumuloItemRetriever.class);
private final Iterator<? extends SEED_TYPE> ids;
protected AccumuloItemRetriever(final AccumuloStore store, final OP_TYPE operation,
final IteratorSetting... iteratorSettings) throws StoreException {
super(store, operation, iteratorSettings);
this.ids = operation.getSeeds().iterator();
}
@Override
public Iterator<Element> iterator() {
if (!ids.hasNext()) {
return Collections.emptyIterator();
}
try {
iterator = new ElementIterator();
} catch (final RetrieverException e) {
LOGGER.error(e.getMessage() + " returning empty iterator", e);
return Collections.emptyIterator();
}
return iterator;
}
protected abstract void addToRanges(final SEED_TYPE seed, final Set<Range> ranges) throws RangeFactoryException;
protected class ElementIterator implements CloseableIterator<Element> {
private final Iterator<? extends SEED_TYPE> idsIterator;
private int count;
private BatchScanner scanner;
private Iterator<Map.Entry<Key, Value>> scannerIterator;
protected ElementIterator() throws RetrieverException {
idsIterator = ids;
count = 0;
final Set<Range> ranges = new HashSet<>();
while (idsIterator.hasNext() && count < store.getProperties().getMaxEntriesForBatchScanner()) {
count++;
try {
addToRanges(idsIterator.next(), ranges);
} catch (final RangeFactoryException e) {
LOGGER.error("Failed to create a range from given seed pair", e);
}
}
// Create BatchScanner, appropriately configured (i.e. ranges,
// iterators, etc).
try {
scanner = getScanner(ranges);
} catch (TableNotFoundException | StoreException e) {
throw new RetrieverException(e);
}
scannerIterator = scanner.iterator();
}
@Override
public boolean hasNext() {
// If current scanner has next then return true.
if (scannerIterator.hasNext()) {
return true;
}
// If current scanner is spent then go back to the iterator
// through the provided entities, and see if there are more.
// If so create the next scanner, if there are no more entities
// then return false.
while (idsIterator.hasNext() && !scannerIterator.hasNext()) {
count = 0;
final Set<Range> ranges = new HashSet<>();
while (idsIterator.hasNext() && count < store.getProperties().getMaxEntriesForBatchScanner()) {
count++;
try {
addToRanges(idsIterator.next(), ranges);
} catch (final RangeFactoryException e) {
LOGGER.error("Failed to create a range from given seed", e);
}
}
scanner.close();
try {
scanner = getScanner(ranges);
} catch (TableNotFoundException | StoreException e) {
LOGGER.error(e.getMessage() + " returning iterator doesn't have any more elements", e);
return false;
}
scannerIterator = scanner.iterator();
}
if (!scannerIterator.hasNext()) {
scanner.close();
}
return scannerIterator.hasNext();
}
@Override
public Element next() {
final Map.Entry<Key, Value> entry = scannerIterator.next();
try {
final Element elm = elementConverter.getFullElement(entry.getKey(), entry.getValue(),
operation.getOptions());
doTransformation(elm);
return elm;
} catch (final AccumuloElementConversionException e) {
LOGGER.error("Failed to re-create an element from a key value entry set returning next element as null",
e);
return null;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("Unable to remove elements from this iterator");
}
@Override
public void close() {
if (scanner != null) {
scanner.close();
}
}
}
}
| gh-104
Call .iterator() on any provided seeds when .iterator() called on the retriever, should allow chains to be re-executed properly.
| accumulo-store/src/main/java/gaffer/accumulostore/retriever/AccumuloItemRetriever.java | gh-104 Call .iterator() on any provided seeds when .iterator() called on the retriever, should allow chains to be re-executed properly. |
|
Java | apache-2.0 | 520198c6ba0bc56aa8ab846d7686096a373d6328 | 0 | rde8026/TwitterClient,rde8026/TwitterClient | package com.eldridge.twitsync.service;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.eldridge.twitsync.controller.TwitterApiController;
import com.google.android.gms.gcm.GoogleCloudMessaging;
/**
* Created by ryaneldridge on 8/13/13.
*/
public class GcmIntentService extends IntentService {
private static final String TAG = GcmIntentService.class.getSimpleName();
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
final Context context = this;
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equalsIgnoreCase(messageType)) {
Log.e(TAG, "** Got Error Message form GCM **");
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equalsIgnoreCase(messageType)) {
Log.d(TAG, "** Deleted Message on Server ***");
} else {
if (extras != null && !extras.isEmpty()) {
final String lastMessage = extras.getString("messageId");
Log.d(TAG, "** Received Notification that another device has read further along - updating **");
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
if (!"".equalsIgnoreCase(lastMessage)) {
TwitterApiController.getInstance(context).syncFromGcm(Long.valueOf(lastMessage));
}
return null;
}
}.execute();
}
}
}
}
| TwitterSync/src/main/java/com/eldridge/twitsync/service/GcmIntentService.java | package com.eldridge.twitsync.service;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
/**
* Created by ryaneldridge on 8/13/13.
*/
public class GcmIntentService extends IntentService {
private static final String TAG = GcmIntentService.class.getSimpleName();
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equalsIgnoreCase(messageType)) {
Log.e(TAG, "** Got Error Message form GCM **");
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equalsIgnoreCase(messageType)) {
Log.d(TAG, "** Deleted Message on Server ***");
} else {
if (extras != null && !extras.isEmpty()) {
String lastMessage = extras.getString("messageId");
Log.d(TAG, "***************** Last Message: " + lastMessage + " **********************");
}
}
}
}
| added async task to deal with updating tweets when GCM notification is sent.
| TwitterSync/src/main/java/com/eldridge/twitsync/service/GcmIntentService.java | added async task to deal with updating tweets when GCM notification is sent. |
|
Java | apache-2.0 | c8312725e68c3c2abb4ac7aa16e59a0d05e64058 | 0 | sylvanmist/Web-Karma,usc-isi-i2/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma,usc-isi-i2/Web-Karma,usc-isi-i2/Web-Karma,usc-isi-i2/Web-Karma,usc-isi-i2/Web-Karma,rpiotti/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma,rpiotti/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma,sylvanmist/Web-Karma | /*******************************************************************************
* Copyright 2012 University of Southern California
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This code was developed by the Information Integration Group as part
* of the Karma project at the Information Sciences Institute of the
* University of Southern California. For more information, publications,
* and related projects, please see: http://www.isi.edu/integration
******************************************************************************/
package edu.isi.karma.controller.history;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.isi.karma.controller.command.Command;
import edu.isi.karma.controller.command.CommandException;
import edu.isi.karma.controller.command.CommandFactory;
import edu.isi.karma.controller.command.ICommand.CommandTag;
import edu.isi.karma.controller.history.CommandHistory.HistoryArguments;
import edu.isi.karma.controller.history.HistoryJsonUtil.ClientJsonKeys;
import edu.isi.karma.controller.history.HistoryJsonUtil.ParameterType;
import edu.isi.karma.controller.update.AbstractUpdate;
import edu.isi.karma.controller.update.TrivialErrorUpdate;
import edu.isi.karma.controller.update.UpdateContainer;
import edu.isi.karma.modeling.alignment.AlignmentManager;
import edu.isi.karma.rep.HNode;
import edu.isi.karma.rep.HNode.HNodeType;
import edu.isi.karma.rep.HTable;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.util.Util;
import edu.isi.karma.webserver.ExecutionController;
import edu.isi.karma.webserver.KarmaException;
import edu.isi.karma.webserver.WorkspaceRegistry;
public class WorksheetCommandHistoryExecutor {
private final String worksheetId;
private final Workspace workspace;
private static Logger logger = LoggerFactory.getLogger(WorksheetCommandHistoryExecutor.class);
private static String[] commandsIgnoreNodeBefore = { "AddColumnCommand",
"SubmitPythonTransformationCommand"
};
public WorksheetCommandHistoryExecutor(String worksheetId, Workspace workspace) {
super();
this.worksheetId = worksheetId;
this.workspace = workspace;
}
public UpdateContainer executeCommandsByTags(
List<CommandTag> tags, JSONArray historyJson) throws JSONException,
KarmaException, CommandException {
JSONArray filteredCommands = HistoryJsonUtil.filterCommandsByTag(tags, historyJson);
return executeAllCommands(filteredCommands);
}
public UpdateContainer executeAllCommands(JSONArray historyJson)
throws JSONException, KarmaException, CommandException {
UpdateContainer uc =new UpdateContainer();
boolean saveToHistory = false;
for (int i = 0; i< historyJson.length(); i++) {
JSONObject commObject = (JSONObject) historyJson.get(i);
if(i == historyJson.length() - 1) saveToHistory = true;
UpdateContainer update = executeCommand(commObject, saveToHistory);
if(update != null)
uc.append(update);
}
return uc;
}
private UpdateContainer executeCommand(JSONObject commObject, boolean saveToHistory)
throws JSONException, KarmaException, CommandException {
ExecutionController ctrl = WorkspaceRegistry.getInstance().getExecutionController(workspace.getId());
HashMap<String, CommandFactory> commandFactoryMap = ctrl.getCommandFactoryMap();
JSONArray inputParamArr = (JSONArray) commObject.get(HistoryArguments.inputParameters.name());
String commandName = (String)commObject.get(HistoryArguments.commandName.name());
logger.info("Command in history: " + commandName);
// Change the hNode ids, vworksheet id to point to the current worksheet ids
try {
UpdateContainer uc = normalizeCommandHistoryJsonInput(workspace, worksheetId, inputParamArr, commandName);
// Invoke the command
if (uc == null) {
uc = new UpdateContainer();
}
CommandFactory cf = commandFactoryMap.get(commObject.get(HistoryArguments.commandName.name()));
if(cf != null) {
try { // This is sort of a hack the way I did this, but could not think of a better way to get rid of the dependency
Command comm = cf.createCommand(inputParamArr, workspace);
if(comm != null){
try {
logger.info("Executing command: " + commandName);
uc.append(workspace.getCommandHistory().doCommand(comm, workspace, saveToHistory));
} catch(Exception e) {
logger.error("Error executing command: "+ commandName + ". Please notify this error");
Util.logException(logger, e);
//make these InfoUpdates so that the UI can still process the rest of the model
return new UpdateContainer(new TrivialErrorUpdate("Error executing command " + commandName + " from history"));
}
}
else {
logger.error("Error occured while creating command (Could not create Command object): "
+ commObject.get(HistoryArguments.commandName.name()));
return new UpdateContainer(new TrivialErrorUpdate("Error executing command " + commandName + " from history"));
}
} catch (UnsupportedOperationException ignored) {
}
}
return uc;
} catch(Exception e) {
logger.error("Error executing command: "+ commandName + ".", e);
//make these InfoUpdates so that the UI can still process the rest of the model
return new UpdateContainer(new TrivialErrorUpdate("Error executing command " + commandName + " from history"));
}
}
private boolean ignoreIfBeforeColumnDoesntExist(String commandName) {
boolean ignore = false;
for(String ignoreCom : commandsIgnoreNodeBefore) {
if(commandName.equals(ignoreCom)) {
ignore = true;
break;
}
}
return ignore;
}
public UpdateContainer normalizeCommandHistoryJsonInput(Workspace workspace, String worksheetId,
JSONArray inputArr, String commandName) throws JSONException {
UpdateContainer uc = null;
HTable hTable = workspace.getWorksheet(worksheetId).getHeaders();
for (int i = 0; i < inputArr.length(); i++) {
JSONObject inpP = inputArr.getJSONObject(i);
if (inpP.getString(ClientJsonKeys.name.name()).equals("outputColumns") || inpP.getString(ClientJsonKeys.name.name()).equals("inputColumns"))
continue;
/*** Check the input parameter type and accordingly make changes ***/
if(HistoryJsonUtil.getParameterType(inpP) == ParameterType.hNodeId) {
JSONArray hNodeJSONRep = new JSONArray(inpP.get(ClientJsonKeys.value.name()).toString());
for (int j=0; j<hNodeJSONRep.length(); j++) {
JSONObject cNameObj = (JSONObject) hNodeJSONRep.get(j);
if(hTable == null) {
AbstractUpdate update = new TrivialErrorUpdate("null HTable while normalizing JSON input for the command " + commandName);
if (uc == null)
uc = new UpdateContainer(update);
else
uc.add(update);
continue;
}
String nameObjColumnName = cNameObj.getString("columnName");
logger.debug("Column being normalized: "+ nameObjColumnName);
HNode node = hTable.getHNodeFromColumnName(nameObjColumnName);
if(node == null) { //Because add column can happen even if the column after which it is to be added is not present
AbstractUpdate update = new TrivialErrorUpdate(nameObjColumnName + " does not exist, using empty values");
if (uc == null)
uc = new UpdateContainer(update);
else
uc.add(update);
hTable.addHNode(nameObjColumnName, HNodeType.Regular, workspace.getWorksheet(worksheetId), workspace.getFactory());
}
if (j == hNodeJSONRep.length()-1) { // Found!
if(node != null)
inpP.put(ClientJsonKeys.value.name(), node.getId());
else {
//Get the id of the last node in the table
ArrayList<String> allNodeIds = hTable.getOrderedNodeIds();
//TODO check for allNodeIds.size == 0
String lastNodeId = allNodeIds.get(allNodeIds.size()-1);
inpP.put(ClientJsonKeys.value.name(), lastNodeId);
}
hTable = workspace.
getWorksheet(worksheetId).getHeaders();
} else if(node != null) {
hTable = node.getNestedTable();
if (hTable == null) {
hTable = node.addNestedTable("NestedTable", workspace.getWorksheet(worksheetId), workspace.getFactory());
}
}
}
} else if(HistoryJsonUtil.getParameterType(inpP) == ParameterType.worksheetId) {
inpP.put(ClientJsonKeys.value.name(), worksheetId);
} else if (HistoryJsonUtil.getParameterType(inpP) == ParameterType.hNodeIdList) {
JSONArray hNodes = new JSONArray(inpP.get(ClientJsonKeys.value.name()).toString());
for (int k = 0; k < hNodes.length(); k++) {
JSONObject hnodeJSON = hNodes.getJSONObject(k);
JSONArray hNodeJSONRep = new JSONArray(hnodeJSON.get(ClientJsonKeys.value.name()).toString());
for (int j=0; j<hNodeJSONRep.length(); j++) {
JSONObject cNameObj = (JSONObject) hNodeJSONRep.get(j);
if(hTable == null) {
AbstractUpdate update = new TrivialErrorUpdate("null HTable while normalizing JSON input for the command " + commandName);
if (uc == null)
uc = new UpdateContainer(update);
else
uc.add(update);
continue;
}
String nameObjColumnName = cNameObj.getString("columnName");
logger.debug("Column being normalized: "+ nameObjColumnName);
HNode node = hTable.getHNodeFromColumnName(nameObjColumnName);
if(node == null) { //Because add column can happen even if the column after which it is to be added is not present
AbstractUpdate update = new TrivialErrorUpdate(nameObjColumnName + " does not exist, using empty values");
if (uc == null)
uc = new UpdateContainer(update);
else
uc.add(update);
hTable.addHNode(nameObjColumnName, HNodeType.Regular, workspace.getWorksheet(worksheetId), workspace.getFactory());
}
if (j == hNodeJSONRep.length()-1) { // Found!
if(node != null)
hnodeJSON.put(ClientJsonKeys.value.name(), node.getId());
else {
//Get the id of the last node in the table
ArrayList<String> allNodeIds = hTable.getOrderedNodeIds();
String lastNodeId = allNodeIds.get(allNodeIds.size()-1);
hnodeJSON.put(ClientJsonKeys.value.name(), lastNodeId);
}
hTable = workspace.
getWorksheet(worksheetId).getHeaders();
} else if(node != null) {
hTable = node.getNestedTable();
if (hTable == null) {
hTable = node.addNestedTable("NestedTable", workspace.getWorksheet(worksheetId), workspace.getFactory());
}
}
}
}
inpP.put(ClientJsonKeys.value.name(), hNodes.toString());
}
else if (HistoryJsonUtil.getParameterType(inpP) == ParameterType.orderedColumns) {
JSONArray hNodes = new JSONArray(inpP.get(ClientJsonKeys.value.name()).toString());
for (int k = 0; k < hNodes.length(); k++) {
JSONObject hnodeJSON = hNodes.getJSONObject(k);
JSONArray hNodeJSONRep = new JSONArray(hnodeJSON.get(ClientJsonKeys.id.name()).toString());
processHNodeId(hNodeJSONRep, hTable, commandName, hnodeJSON);
if (hnodeJSON.has(ClientJsonKeys.children.name())) {
JSONArray children = new JSONArray(hnodeJSON.get(ClientJsonKeys.children.name()).toString());
hnodeJSON.put(ClientJsonKeys.children.name(), processChildren(children, hTable, commandName));
}
}
inpP.put(ClientJsonKeys.value.name(), hNodes.toString());
}
}
AlignmentManager.Instance().getAlignmentOrCreateIt(workspace.getId(), worksheetId, workspace.getOntologyManager());
return uc;
}
private boolean processHNodeId(JSONArray hNodeJSONRep, HTable hTable, String commandName, JSONObject hnodeJSON) {
for (int j=0; j<hNodeJSONRep.length(); j++) {
JSONObject cNameObj = (JSONObject) hNodeJSONRep.get(j);
if(hTable == null) {
return false;
}
String nameObjColumnName = cNameObj.getString("columnName");
logger.debug("Column being normalized: "+ nameObjColumnName);
HNode node = hTable.getHNodeFromColumnName(nameObjColumnName);
if(node == null && !ignoreIfBeforeColumnDoesntExist(commandName)) { //Because add column can happen even if the column after which it is to be added is not present
logger.info("null HNode " + nameObjColumnName + " while normalizing JSON input for the command " + commandName);
return false;
}
if (j == hNodeJSONRep.length()-1) { // Found!
if(node != null)
hnodeJSON.put(ClientJsonKeys.id.name(), node.getId());
else {
//Get the id of the last node in the table
ArrayList<String> allNodeIds = hTable.getOrderedNodeIds();
String lastNodeId = allNodeIds.get(allNodeIds.size()-1);
hnodeJSON.put(ClientJsonKeys.id.name(), lastNodeId);
}
hTable = workspace.
getWorksheet(worksheetId).getHeaders();
} else if(node != null) {
hTable = node.getNestedTable();
}
}
return true;
}
private JSONArray processChildren(JSONArray children, HTable hTable, String commandName) {
for (int i = 0; i < children.length(); i++) {
JSONObject obj = children.getJSONObject(i);
JSONArray array = new JSONArray(obj.get(ClientJsonKeys.id.name()).toString());
processHNodeId(array, hTable, commandName, obj);
if (obj.has(ClientJsonKeys.children.name())) {
obj.put(ClientJsonKeys.children.name(), processChildren(new JSONArray(obj.get(ClientJsonKeys.children.name()).toString()), hTable, commandName));
}
}
return children;
}
}
| karma-common/src/main/java/edu/isi/karma/controller/history/WorksheetCommandHistoryExecutor.java | /*******************************************************************************
* Copyright 2012 University of Southern California
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This code was developed by the Information Integration Group as part
* of the Karma project at the Information Sciences Institute of the
* University of Southern California. For more information, publications,
* and related projects, please see: http://www.isi.edu/integration
******************************************************************************/
package edu.isi.karma.controller.history;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.isi.karma.controller.command.Command;
import edu.isi.karma.controller.command.CommandException;
import edu.isi.karma.controller.command.CommandFactory;
import edu.isi.karma.controller.command.ICommand.CommandTag;
import edu.isi.karma.controller.history.CommandHistory.HistoryArguments;
import edu.isi.karma.controller.history.HistoryJsonUtil.ClientJsonKeys;
import edu.isi.karma.controller.history.HistoryJsonUtil.ParameterType;
import edu.isi.karma.controller.update.AbstractUpdate;
import edu.isi.karma.controller.update.TrivialErrorUpdate;
import edu.isi.karma.controller.update.UpdateContainer;
import edu.isi.karma.rep.HNode;
import edu.isi.karma.rep.HTable;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.util.Util;
import edu.isi.karma.webserver.ExecutionController;
import edu.isi.karma.webserver.KarmaException;
import edu.isi.karma.webserver.WorkspaceRegistry;
public class WorksheetCommandHistoryExecutor {
private final String worksheetId;
private final Workspace workspace;
private static Logger logger = LoggerFactory.getLogger(WorksheetCommandHistoryExecutor.class);
private static String[] commandsIgnoreNodeBefore = { "AddColumnCommand",
"SubmitPythonTransformationCommand"
};
public WorksheetCommandHistoryExecutor(String worksheetId, Workspace workspace) {
super();
this.worksheetId = worksheetId;
this.workspace = workspace;
}
public UpdateContainer executeCommandsByTags(
List<CommandTag> tags, JSONArray historyJson) throws JSONException,
KarmaException, CommandException {
JSONArray filteredCommands = HistoryJsonUtil.filterCommandsByTag(tags, historyJson);
return executeAllCommands(filteredCommands);
}
public UpdateContainer executeAllCommands(JSONArray historyJson)
throws JSONException, KarmaException, CommandException {
UpdateContainer uc =new UpdateContainer();
boolean saveToHistory = false;
for (int i = 0; i< historyJson.length(); i++) {
JSONObject commObject = (JSONObject) historyJson.get(i);
if(i == historyJson.length() - 1) saveToHistory = true;
UpdateContainer update = executeCommand(commObject, saveToHistory);
if(update != null)
uc.append(update);
}
return uc;
}
private UpdateContainer executeCommand(JSONObject commObject, boolean saveToHistory)
throws JSONException, KarmaException, CommandException {
ExecutionController ctrl = WorkspaceRegistry.getInstance().getExecutionController(workspace.getId());
HashMap<String, CommandFactory> commandFactoryMap = ctrl.getCommandFactoryMap();
JSONArray inputParamArr = (JSONArray) commObject.get(HistoryArguments.inputParameters.name());
String commandName = (String)commObject.get(HistoryArguments.commandName.name());
logger.info("Command in history: " + commandName);
// Change the hNode ids, vworksheet id to point to the current worksheet ids
try {
UpdateContainer uc = normalizeCommandHistoryJsonInput(workspace, worksheetId, inputParamArr, commandName);
if(uc == null) { //No error
// Invoke the command
uc = new UpdateContainer();
CommandFactory cf = commandFactoryMap.get(commObject.get(HistoryArguments.commandName.name()));
if(cf != null) {
try { // This is sort of a hack the way I did this, but could not think of a better way to get rid of the dependency
Command comm = cf.createCommand(inputParamArr, workspace);
if(comm != null){
try {
logger.info("Executing command: " + commandName);
uc.append(workspace.getCommandHistory().doCommand(comm, workspace, saveToHistory));
} catch(Exception e) {
logger.error("Error executing command: "+ commandName + ". Please notify this error");
Util.logException(logger, e);
//make these InfoUpdates so that the UI can still process the rest of the model
return new UpdateContainer(new TrivialErrorUpdate("Error executing command " + commandName + " from history"));
}
}
else {
logger.error("Error occured while creating command (Could not create Command object): "
+ commObject.get(HistoryArguments.commandName.name()));
return new UpdateContainer(new TrivialErrorUpdate("Error executing command " + commandName + " from history"));
}
} catch (UnsupportedOperationException ignored) {
}
}
}
return uc;
} catch(Exception e) {
logger.error("Error executing command: "+ commandName + ". Please notify this error");
Util.logException(logger, e);
//make these InfoUpdates so that the UI can still process the rest of the model
return new UpdateContainer(new TrivialErrorUpdate("Error executing command " + commandName + " from history"));
}
}
private boolean ignoreIfBeforeColumnDoesntExist(String commandName) {
boolean ignore = false;
for(String ignoreCom : commandsIgnoreNodeBefore) {
if(commandName.equals(ignoreCom)) {
ignore = true;
break;
}
}
return ignore;
}
public UpdateContainer normalizeCommandHistoryJsonInput(Workspace workspace, String worksheetId,
JSONArray inputArr, String commandName) throws JSONException {
UpdateContainer uc = null;
HTable hTable = workspace.getWorksheet(worksheetId).getHeaders();
for (int i = 0; i < inputArr.length(); i++) {
JSONObject inpP = inputArr.getJSONObject(i);
if (inpP.getString(ClientJsonKeys.name.name()).equals("outputColumns") || inpP.getString(ClientJsonKeys.name.name()).equals("inputColumns"))
continue;
/*** Check the input parameter type and accordingly make changes ***/
if(HistoryJsonUtil.getParameterType(inpP) == ParameterType.hNodeId) {
JSONArray hNodeJSONRep = new JSONArray(inpP.get(ClientJsonKeys.value.name()).toString());
for (int j=0; j<hNodeJSONRep.length(); j++) {
JSONObject cNameObj = (JSONObject) hNodeJSONRep.get(j);
if(hTable == null) {
AbstractUpdate update = new TrivialErrorUpdate("null HTable while normalizing JSON input for the command " + commandName);
if (uc == null)
uc = new UpdateContainer(update);
else
uc.add(update);
continue;
}
String nameObjColumnName = cNameObj.getString("columnName");
logger.debug("Column being normalized: "+ nameObjColumnName);
HNode node = hTable.getHNodeFromColumnName(nameObjColumnName);
if(node == null && !ignoreIfBeforeColumnDoesntExist(commandName)) { //Because add column can happen even if the column after which it is to be added is not present
logger.info("null HNode " + nameObjColumnName + " while normalizing JSON input for the command " + commandName);
AbstractUpdate update = new TrivialErrorUpdate("Column " + nameObjColumnName + " does not exist. " +
"All commands for this column are being skipped. You can add the column to the data or Worksheet and apply the model again.");
if (uc == null)
uc = new UpdateContainer(update);
else
uc.add(update);
continue;
}
if (j == hNodeJSONRep.length()-1) { // Found!
if(node != null)
inpP.put(ClientJsonKeys.value.name(), node.getId());
else {
//Get the id of the last node in the table
ArrayList<String> allNodeIds = hTable.getOrderedNodeIds();
String lastNodeId = allNodeIds.get(allNodeIds.size()-1);
inpP.put(ClientJsonKeys.value.name(), lastNodeId);
}
hTable = workspace.
getWorksheet(worksheetId).getHeaders();
} else if(node != null) {
hTable = node.getNestedTable();
}
}
} else if(HistoryJsonUtil.getParameterType(inpP) == ParameterType.worksheetId) {
inpP.put(ClientJsonKeys.value.name(), worksheetId);
} else if (HistoryJsonUtil.getParameterType(inpP) == ParameterType.hNodeIdList) {
JSONArray hNodes = new JSONArray(inpP.get(ClientJsonKeys.value.name()).toString());
for (int k = 0; k < hNodes.length(); k++) {
JSONObject hnodeJSON = hNodes.getJSONObject(k);
JSONArray hNodeJSONRep = new JSONArray(hnodeJSON.get(ClientJsonKeys.value.name()).toString());
for (int j=0; j<hNodeJSONRep.length(); j++) {
JSONObject cNameObj = (JSONObject) hNodeJSONRep.get(j);
if(hTable == null) {
AbstractUpdate update = new TrivialErrorUpdate("null HTable while normalizing JSON input for the command " + commandName);
if (uc == null)
uc = new UpdateContainer(update);
else
uc.add(update);
continue;
}
String nameObjColumnName = cNameObj.getString("columnName");
logger.debug("Column being normalized: "+ nameObjColumnName);
HNode node = hTable.getHNodeFromColumnName(nameObjColumnName);
if(node == null && !ignoreIfBeforeColumnDoesntExist(commandName)) { //Because add column can happen even if the column after which it is to be added is not present
logger.info("null HNode " + nameObjColumnName + " while normalizing JSON input for the command " + commandName);
AbstractUpdate update = new TrivialErrorUpdate("Column " + nameObjColumnName + " does not exist. " +
"All commands for this column are being skipped. You can add the column to the data or Worksheet and apply the model again.");
if (uc == null)
uc = new UpdateContainer(update);
else
uc.add(update);
continue;
//return false;
}
if (j == hNodeJSONRep.length()-1) { // Found!
if(node != null)
hnodeJSON.put(ClientJsonKeys.value.name(), node.getId());
else {
//Get the id of the last node in the table
ArrayList<String> allNodeIds = hTable.getOrderedNodeIds();
String lastNodeId = allNodeIds.get(allNodeIds.size()-1);
hnodeJSON.put(ClientJsonKeys.value.name(), lastNodeId);
}
hTable = workspace.
getWorksheet(worksheetId).getHeaders();
} else if(node != null) {
hTable = node.getNestedTable();
}
}
}
inpP.put(ClientJsonKeys.value.name(), hNodes.toString());
}
else if (HistoryJsonUtil.getParameterType(inpP) == ParameterType.orderedColumns) {
JSONArray hNodes = new JSONArray(inpP.get(ClientJsonKeys.value.name()).toString());
for (int k = 0; k < hNodes.length(); k++) {
JSONObject hnodeJSON = hNodes.getJSONObject(k);
JSONArray hNodeJSONRep = new JSONArray(hnodeJSON.get(ClientJsonKeys.id.name()).toString());
processHNodeId(hNodeJSONRep, hTable, commandName, hnodeJSON);
if (hnodeJSON.has(ClientJsonKeys.children.name())) {
JSONArray children = new JSONArray(hnodeJSON.get(ClientJsonKeys.children.name()).toString());
hnodeJSON.put(ClientJsonKeys.children.name(), processChildren(children, hTable, commandName));
}
}
inpP.put(ClientJsonKeys.value.name(), hNodes.toString());
}
}
return uc;
}
private boolean processHNodeId(JSONArray hNodeJSONRep, HTable hTable, String commandName, JSONObject hnodeJSON) {
for (int j=0; j<hNodeJSONRep.length(); j++) {
JSONObject cNameObj = (JSONObject) hNodeJSONRep.get(j);
if(hTable == null) {
return false;
}
String nameObjColumnName = cNameObj.getString("columnName");
logger.debug("Column being normalized: "+ nameObjColumnName);
HNode node = hTable.getHNodeFromColumnName(nameObjColumnName);
if(node == null && !ignoreIfBeforeColumnDoesntExist(commandName)) { //Because add column can happen even if the column after which it is to be added is not present
logger.info("null HNode " + nameObjColumnName + " while normalizing JSON input for the command " + commandName);
return false;
}
if (j == hNodeJSONRep.length()-1) { // Found!
if(node != null)
hnodeJSON.put(ClientJsonKeys.id.name(), node.getId());
else {
//Get the id of the last node in the table
ArrayList<String> allNodeIds = hTable.getOrderedNodeIds();
String lastNodeId = allNodeIds.get(allNodeIds.size()-1);
hnodeJSON.put(ClientJsonKeys.id.name(), lastNodeId);
}
hTable = workspace.
getWorksheet(worksheetId).getHeaders();
} else if(node != null) {
hTable = node.getNestedTable();
}
}
return true;
}
private JSONArray processChildren(JSONArray children, HTable hTable, String commandName) {
for (int i = 0; i < children.length(); i++) {
JSONObject obj = children.getJSONObject(i);
JSONArray array = new JSONArray(obj.get(ClientJsonKeys.id.name()).toString());
processHNodeId(array, hTable, commandName, obj);
if (obj.has(ClientJsonKeys.children.name())) {
obj.put(ClientJsonKeys.children.name(), processChildren(new JSONArray(obj.get(ClientJsonKeys.children.name()).toString()), hTable, commandName));
}
}
return children;
}
}
| handling missing columns in Glue Command
| karma-common/src/main/java/edu/isi/karma/controller/history/WorksheetCommandHistoryExecutor.java | handling missing columns in Glue Command |
|
Java | apache-2.0 | 7d3a62bcaf6c72c82b460e0369ea26223672826f | 0 | mohanaraosv/commons-imaging,SpiralsSeminaire/commons-imaging,mohanaraosv/commons-imaging,apache/commons-imaging,yuuhayashi/commons-imaging,SpiralsSeminaire/commons-imaging,apache/commons-imaging,yuuhayashi/commons-imaging | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.imaging.formats.bmp;
class ImageContents {
final BmpHeaderInfo bhi;
final byte[] colorTable;
final byte[] imageData;
final PixelParser pixelParser;
public ImageContents(BmpHeaderInfo bhi, byte[] colorTable, byte[] imageData, PixelParser pixelParser) {
this.bhi = bhi;
this.colorTable = colorTable;
this.imageData = imageData;
this.pixelParser = pixelParser;
}
}
| src/main/java/org/apache/commons/imaging/formats/bmp/ImageContents.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.imaging.formats.bmp;
class ImageContents {
public final BmpHeaderInfo bhi;
public final byte[] colorTable;
public final byte[] imageData;
public final PixelParser pixelParser;
public ImageContents(BmpHeaderInfo bhi, byte[] colorTable, byte[] imageData, PixelParser pixelParser) {
this.bhi = bhi;
this.colorTable = colorTable;
this.imageData = imageData;
this.pixelParser = pixelParser;
}
}
| No need for these to be public
git-svn-id: ef215b97ec449bc9c69e2ae1448853f14b3d8f41@1648331 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/imaging/formats/bmp/ImageContents.java | No need for these to be public |
|
Java | apache-2.0 | 3d67be147eca0cf60c0644e0ad4e9b58c246b8a2 | 0 | eirbjo/jetty-console,eirbjo/jetty-console | /*
* Copyright 2015 Eirik Bjørsnøs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.simplericity.jettyconsole;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.simplericity.jettyconsole.creator.Creator;
import org.simplericity.jettyconsole.creator.CreatorExecutionException;
import org.simplericity.jettyconsole.creator.DefaultCreator;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.jar.JarFile;
/**
* This plugin creates a jar embedding Jetty and a webapp. Double clicking the jar starts a graphical console
* that lets the user select a port and start/stop the webapp.
*
* This is intended to be an easy way to distribute webapps for review/testing etc without the need to distribute and/or
* configure a servlet container.
*
* @goal createconsole
*
* @phase package
*
* @requiresDependencyResolution runtime
*/
public class CreateDescriptorMojo
extends AbstractMojo {
/**
* Archive configuration to read MANIFEST.MF entries from.
* @parameter
*/
private MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
/**
* Directory containing the classes.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
*/
private File classesDirectory;
/**
* Name of the console project. Used in frame title and dialogs
*
* @parameter default-value="${project.name} ${project.version}"
*/
private String name;
/**
* Background image to use for the console instead of the default.
* @parameter
*/
private File backgroundImage;
/**
* The Maven Project Object
* @parameter expression="${project}"
*/
private MavenProject project;
/**
* Working directory where dependencies are unpacked before repackaging
* @parameter default-value="${project.build.directory}/console-work"
*/
private File workingDirectory;
/**
* Classifier for the executable war
*
* @parameter default-value="jetty-console"
*/
private String jettyConsoleClassifier;
/**
* Destination file for the packaged console. An error will be thrown if classifier is not present in the filename
*
* @parameter default-value="${project.build.directory}/${project.build.finalName}-${jettyConsoleClassifier}.war"
*/
private File destinationFile;
/**
* Artifact to make executable
*
* @parameter
*/
private Dependency artifactToMakeExecutable;
/**
* Any additional dependencies to include on the Jetty console class path
* @parameter
*/
private List<AdditionalDependency> additionalDependencies;
/**
* Maven ProjectHelper
* @component
* @readonly
*/
private MavenProjectHelper projectHelper;
/** @component */
private org.apache.maven.artifact.factory.ArtifactFactory artifactFactory;
/** @component */
private org.apache.maven.artifact.resolver.ArtifactResolver resolver;
/**@parameter expression="${localRepository}" */
private org.apache.maven.artifact.repository.ArtifactRepository localRepository;
/** @parameter expression="${project.remoteArtifactRepositories}" */
private java.util.List remoteRepositories;
/** @component */
private ArtifactMetadataSource artifactMetadataSource;
private Creator creator;
/**
* @parameter default-value="true"
*/
private boolean attachWithClassifier;
/**
* @parameter default-value=""
*/
private String properties;
private Properties props;
private final String JETTY_CONSOLE_CLASSIFIER_PARAM_NAME = "jettyConsoleClassifier";
public void execute()
throws MojoExecutionException, MojoFailureException {
getProps();
// Check that the background image exists
if(backgroundImage != null && !backgroundImage.exists()) {
throw new MojoExecutionException("The 'backgroundImage' file you specified does not exist");
}
// Replace ${jettyConsoleClassifier} with actual value...
if (destinationFile.getName().contains("${" + JETTY_CONSOLE_CLASSIFIER_PARAM_NAME + "}")) {
String existingFileName = destinationFile.getName();
String newFileName = existingFileName.replace("${" + JETTY_CONSOLE_CLASSIFIER_PARAM_NAME + "}", jettyConsoleClassifier);
destinationFile = new File(destinationFile.getParent(), newFileName);
}
// Classifier must be present in destination file
if (!destinationFile.getName().contains(jettyConsoleClassifier)) {
throw new MojoExecutionException("Parameter 'destinationFile' (" + destinationFile.getName() + ") does not contain the configured value for'jettyConsoleClassifier' (" + jettyConsoleClassifier + ")");
}
Artifact warArtifact = getWarArtifact();
creator = new DefaultCreator();
creator.setWorkingDirectory(workingDirectory);
creator.setSourceWar(warArtifact.getFile());
creator.setDestinationWar(destinationFile);
creator.setName(name);
creator.setProperties(properties);
creator.setManifestEntries(archive.getManifestEntries());
if(backgroundImage != null && backgroundImage.exists() && backgroundImage.isFile()) {
try {
creator.setBackgroundImage(backgroundImage.toURL());
} catch (MalformedURLException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
setDeps();
try {
getLog().info("Creating JettyConsole package");
creator.create();
} catch (CreatorExecutionException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
if(attachWithClassifier) {
attachArtifact();
} else {
project.getArtifact().setFile(destinationFile);
}
}
private void setDeps() throws MojoExecutionException, MojoFailureException {
List<File> deps = getDependencies();
List<URL> additionalDeps = new ArrayList<URL>();
for (File file : deps) {
if (file.getName().contains("jetty-console-core")) {
try {
creator.setCoreDependency(file.toURL());
} catch (MalformedURLException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
} else {
try {
additionalDeps.add(file.toURL());
} catch (MalformedURLException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
}
Set<Artifact> artifacts = new HashSet<Artifact>();
if (additionalDependencies != null) {
for (AdditionalDependency dep : additionalDependencies) {
String groupId = dep.getGroupId();
String version = dep.getVersion();
if (groupId == null && version == null) {
groupId = "org.simplericity.jettyconsole";
version = props.getProperty("version");
}
artifacts.add(artifactFactory.createDependencyArtifact(groupId, dep.getArtifactId(), VersionRange.createFromVersion(version), dep.getType(), dep.getClassifier(), dep.getScope()));
}
}
try {
Set<Artifact> slf4jBindingArtifacts = new HashSet<Artifact>();
if (artifacts.size() > 0 ) {
ArtifactResolutionResult result = resolver.resolveTransitively(artifacts, project.getArtifact(), localRepository, remoteRepositories, artifactMetadataSource, new ScopeArtifactFilter("runtime"));
for (Artifact artifact : (Set<Artifact>) result.getArtifacts()) {
if (!"slf4j-api".equals(artifact.getArtifactId())) {
additionalDeps.add(artifact.getFile().toURL());
if(hasSlf4jBinding(artifact.getFile())) {
slf4jBindingArtifacts.add(artifact);
}
}
}
}
if (project.getPackaging().equals("jar")) {
additionalDeps.add(project.getArtifact().getFile().toURL());
}
if (slf4jBindingArtifacts.isEmpty()) {
String slf4jVersion = props.getProperty("slf4jVersion");
final Artifact slf4jArtifact = artifactFactory.createDependencyArtifact("org.slf4j", "slf4j-simple", VersionRange.createFromVersion(slf4jVersion), "jar", null, "runtime");
resolver.resolve(slf4jArtifact, remoteRepositories, localRepository);
additionalDeps.add(slf4jArtifact.getFile().toURL());
} else if(slf4jBindingArtifacts.size() > 1) {
throw new MojoFailureException("You have dependencies on multiple SJF4J artifacts, please select a single one: " + slf4jBindingArtifacts);
}
} catch (ArtifactResolutionException | MalformedURLException | ArtifactNotFoundException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
creator.setAdditionalDependecies(additionalDeps);
}
/**
* Returns true if the given jar file contains an SLF4J binding
* @param file the file
* @return true if the jar file contains an SLF4J binding
*/
private boolean hasSlf4jBinding(File file) throws MojoExecutionException {
try (JarFile jarFile = new JarFile(file)){
return jarFile.getEntry("org/slf4j/impl/StaticLoggerBinder.class") != null;
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
private List<File> getDependencies() throws MojoExecutionException {
Set<Artifact> artifacts = new HashSet<>();
String version = props.getProperty("version");
String jettyVersion = props.getProperty("jettyVersion");
getLog().info("Resolving dependencies for version " + version +" of jetty-console-core");
artifacts.add(artifactFactory.createDependencyArtifact("org.simplericity.jettyconsole", "jetty-console-core", VersionRange.createFromVersion(version), "jar", null, "runtime"));
List<File> artifactFiles = new ArrayList<File>();
try {
ArtifactResolutionResult result = resolver.resolveTransitively(artifacts, project.getArtifact(), remoteRepositories, localRepository, artifactMetadataSource);
for(Artifact artifact : (Set<Artifact>) result.getArtifacts()) {
artifactFiles.add(artifact.getFile());
}
return artifactFiles;
} catch (ArtifactResolutionException | ArtifactNotFoundException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
private void getProps() throws MojoExecutionException {
props = new Properties();
try {
props.load(getClass().getClassLoader().getResourceAsStream("pluginversion.properties"));
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
private void attachArtifact() {
projectHelper.attachArtifact(project, "war", jettyConsoleClassifier, destinationFile);
}
public Artifact getWarArtifact() throws MojoExecutionException {
try {
if (artifactToMakeExecutable != null) {
Artifact artifact = artifactFactory.createDependencyArtifact(artifactToMakeExecutable.getGroupId(), artifactToMakeExecutable.getArtifactId(),
VersionRange.createFromVersion(artifactToMakeExecutable.getVersion()), artifactToMakeExecutable.getType(), artifactToMakeExecutable.getClassifier(), "runtime");
resolver.resolve(artifact, remoteRepositories, localRepository);
return artifact;
}
} catch (ArtifactResolutionException e) {
throw new MojoExecutionException("Unable to resolve artifact to make executable (" + e.getMessage() + ")", e);
} catch (ArtifactNotFoundException e) {
throw new MojoExecutionException("Unable to find artifact to make executable (" + e.getMessage() + ")", e);
}
List<Artifact> wars = new ArrayList<Artifact>();
for (Iterator i = project.getArtifacts().iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
if ("war".equals(artifact.getType())) {
wars.add(artifact);
}
}
if(wars.size() == 0) {
throw new MojoExecutionException("Can't find any war dependency");
} else if(wars.size() > 1) {
throw new MojoExecutionException("Found more than one war dependency, can't continue");
} else {
return wars.get(0);
}
}
}
| jetty-console-maven-plugin/src/main/java/org/simplericity/jettyconsole/CreateDescriptorMojo.java | /*
* Copyright 2015 Eirik Bjørsnøs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.simplericity.jettyconsole;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.simplericity.jettyconsole.creator.Creator;
import org.simplericity.jettyconsole.creator.CreatorExecutionException;
import org.simplericity.jettyconsole.creator.DefaultCreator;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.jar.JarFile;
/**
* This plugin creates a jar embedding Jetty and a webapp. Double clicking the jar starts a graphical console
* that lets the user select a port and start/stop the webapp.
*
* This is intended to be an easy way to distribute webapps for review/testing etc without the need to distribute and/or
* configure a servlet container.
*
* @goal createconsole
*
* @phase package
*
* @requiresDependencyResolution runtime
*/
public class CreateDescriptorMojo
extends AbstractMojo
{
/**
* Archive configuration to read MANIFEST.MF entries from.
* @parameter
*/
private MavenArchiveConfiguration archive = new MavenArchiveConfiguration();
/**
* Directory containing the classes.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
*/
private File classesDirectory;
/**
* Name of the console project. Used in frame title and dialogs
*
* @parameter default-value="${project.name} ${project.version}"
*/
private String name;
/**
* Background image to use for the console instead of the default.
* @parameter
*/
private File backgroundImage;
/**
* The Maven Project Object
* @parameter expression="${project}"
*/
private MavenProject project;
/**
* Working directory where dependencies are unpacked before repackaging
* @parameter default-value="${project.build.directory}/console-work"
*/
private File workingDirectory;
/**
* Destination file for the packaged console
* @parameter default-value="${project.build.directory}/${project.build.finalName}-jetty-console.war"
*/
private File destinationFile;
/**
* Any additional dependencies to include on the Jetty console class path
* @parameter
*/
private List<AdditionalDependency> additionalDependencies;
/**
* Maven ProjectHelper
* @component
* @readonly
*/
private MavenProjectHelper projectHelper;
/** @component */
private org.apache.maven.artifact.factory.ArtifactFactory artifactFactory;
/** @component */
private org.apache.maven.artifact.resolver.ArtifactResolver resolver;
/**@parameter expression="${localRepository}" */
private org.apache.maven.artifact.repository.ArtifactRepository localRepository;
/** @parameter expression="${project.remoteArtifactRepositories}" */
private java.util.List remoteRepositories;
/** @component */
private ArtifactMetadataSource artifactMetadataSource;
private Creator creator;
/**
* @parameter default-value="true"
*/
private boolean attachWithClassifier;
/**
* @parameter default-value=""
*/
private String properties;
private Properties props;
public void execute()
throws MojoExecutionException, MojoFailureException {
getProps();
// Check that the background image exists
if(backgroundImage != null && !backgroundImage.exists()) {
throw new MojoExecutionException("The 'backgroundImage' file you specified does not exist");
}
Artifact warArtifact = getWarArtifact();
creator = new DefaultCreator();
creator.setWorkingDirectory(workingDirectory);
creator.setSourceWar(warArtifact.getFile());
creator.setDestinationWar(destinationFile);
creator.setName(name);
creator.setProperties(properties);
creator.setManifestEntries(archive.getManifestEntries());
if(backgroundImage != null && backgroundImage.exists() && backgroundImage.isFile()) {
try {
creator.setBackgroundImage(backgroundImage.toURL());
} catch (MalformedURLException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
setDeps();
try {
getLog().info("Creating JettyConsole package");
creator.create();
} catch (CreatorExecutionException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
if(attachWithClassifier) {
attachArtifact();
} else {
project.getArtifact().setFile(destinationFile);
}
}
private void setDeps() throws MojoExecutionException, MojoFailureException {
List<File> deps = getDependencies();
List<URL> additionalDeps = new ArrayList<URL>();
for (File file : deps) {
if (file.getName().contains("jetty-console-core")) {
try {
creator.setCoreDependency(file.toURL());
} catch (MalformedURLException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
} else {
try {
additionalDeps.add(file.toURL());
} catch (MalformedURLException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
}
Set<Artifact> artifacts = new HashSet<Artifact>();
if (additionalDependencies != null) {
for (AdditionalDependency dep : additionalDependencies) {
String groupId = dep.getGroupId();
String version = dep.getVersion();
if (groupId == null && version == null) {
groupId = "org.simplericity.jettyconsole";
version = props.getProperty("version");
}
artifacts.add(artifactFactory.createDependencyArtifact(groupId, dep.getArtifactId(), VersionRange.createFromVersion(version), dep.getType(), dep.getClassifier(), dep.getScope()));
}
}
try {
Set<Artifact> slf4jBindingArtifacts = new HashSet<Artifact>();
if (artifacts.size() > 0 ) {
ArtifactResolutionResult result = resolver.resolveTransitively(artifacts, project.getArtifact(), localRepository, remoteRepositories, artifactMetadataSource, new ScopeArtifactFilter("runtime"));
for (Artifact artifact : (Set<Artifact>) result.getArtifacts()) {
if (!"slf4j-api".equals(artifact.getArtifactId())) {
additionalDeps.add(artifact.getFile().toURL());
if(hasSlf4jBinding(artifact.getFile())) {
slf4jBindingArtifacts.add(artifact);
}
}
}
}
if (project.getPackaging().equals("jar")) {
additionalDeps.add(project.getArtifact().getFile().toURL());
}
if (slf4jBindingArtifacts.isEmpty()) {
String slf4jVersion = props.getProperty("slf4jVersion");
final Artifact slf4jArtifact = artifactFactory.createDependencyArtifact("org.slf4j", "slf4j-simple", VersionRange.createFromVersion(slf4jVersion), "jar", null, "runtime");
resolver.resolve(slf4jArtifact, remoteRepositories, localRepository);
additionalDeps.add(slf4jArtifact.getFile().toURL());
} else if(slf4jBindingArtifacts.size() > 1) {
throw new MojoFailureException("You have dependencies on multiple SJF4J artifacts, please select a single one: " + slf4jBindingArtifacts);
}
} catch (ArtifactResolutionException | MalformedURLException | ArtifactNotFoundException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
creator.setAdditionalDependecies(additionalDeps);
}
/**
* Returns true if the given jar file contains an SLF4J binding
* @param file the file
* @return true if the jar file contains an SLF4J binding
*/
private boolean hasSlf4jBinding(File file) throws MojoExecutionException {
try (JarFile jarFile = new JarFile(file)){
return jarFile.getEntry("org/slf4j/impl/StaticLoggerBinder.class") != null;
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
private List<File> getDependencies() throws MojoExecutionException {
Set<Artifact> artifacts = new HashSet<>();
String version = props.getProperty("version");
String jettyVersion = props.getProperty("jettyVersion");
getLog().info("Resolving dependencies for version " + version +" of jetty-console-core");
artifacts.add(artifactFactory.createDependencyArtifact("org.simplericity.jettyconsole", "jetty-console-core", VersionRange.createFromVersion(version), "jar", null, "runtime"));
List<File> artifactFiles = new ArrayList<File>();
try {
ArtifactResolutionResult result = resolver.resolveTransitively(artifacts, project.getArtifact(), remoteRepositories, localRepository, artifactMetadataSource);
for(Artifact artifact : (Set<Artifact>) result.getArtifacts()) {
artifactFiles.add(artifact.getFile());
}
return artifactFiles;
} catch (ArtifactResolutionException | ArtifactNotFoundException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
private void getProps() throws MojoExecutionException {
props = new Properties();
try {
props.load(getClass().getClassLoader().getResourceAsStream("pluginversion.properties"));
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
private void attachArtifact() {
projectHelper.attachArtifact(project, "war", "jetty-console", destinationFile);
}
public Artifact getWarArtifact() throws MojoExecutionException {
if(project.getArtifact().getFile().getName().endsWith(".war")) {
return project.getArtifact();
}
List<Artifact> wars = new ArrayList<Artifact>();
for (Iterator i = project.getArtifacts().iterator(); i.hasNext();) {
Artifact artifact = (Artifact) i.next();
if ("war".equals(artifact.getType())) {
wars.add(artifact);
}
}
if(wars.size() == 0) {
throw new MojoExecutionException("Can't find any war dependency");
} else if(wars.size() > 1) {
throw new MojoExecutionException("Found more than one war dependency, can't continue");
} else {
return wars.get(0);
}
}
}
| Added (simple) support for classifiers
| jetty-console-maven-plugin/src/main/java/org/simplericity/jettyconsole/CreateDescriptorMojo.java | Added (simple) support for classifiers |
|
Java | apache-2.0 | b24043ed7f441322230e9195a75e05b4164b828c | 0 | AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid | package me.devsaki.hentoid.fragments.viewer;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.activities.ImageViewerActivity;
import me.devsaki.hentoid.adapters.ImagePagerAdapter;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.databinding.FragmentViewerPagerBinding;
import me.devsaki.hentoid.ui.InputDialog;
import me.devsaki.hentoid.util.Debouncer;
import me.devsaki.hentoid.util.Preferences;
import me.devsaki.hentoid.util.ToastUtil;
import me.devsaki.hentoid.util.exception.ContentNotRemovedException;
import me.devsaki.hentoid.viewmodels.ImageViewerViewModel;
import me.devsaki.hentoid.viewmodels.ViewModelFactory;
import me.devsaki.hentoid.widget.OnZoneTapListener;
import me.devsaki.hentoid.widget.PageSnapWidget;
import me.devsaki.hentoid.widget.PrefetchLinearLayoutManager;
import me.devsaki.hentoid.widget.ScrollPositionListener;
import me.devsaki.hentoid.widget.VolumeKeyListener;
import timber.log.Timber;
import static java.lang.String.format;
import static me.devsaki.hentoid.util.Preferences.Constant;
// TODO : better document and/or encapsulate the difference between
// - paper roll mode (currently used for vertical display)
// - independent page mode (currently used for horizontal display)
public class ViewerPagerFragment extends Fragment implements ViewerBrowseModeDialogFragment.Parent, ViewerPrefsDialogFragment.Parent, ViewerDeleteDialogFragment.Parent {
private static final String KEY_HUD_VISIBLE = "hud_visible";
private static final String KEY_GALLERY_SHOWN = "gallery_shown";
private static final String KEY_SLIDESHOW_ON = "slideshow_on";
private final RequestOptions glideRequestOptions = new RequestOptions().centerInside();
private ImagePagerAdapter adapter;
private PrefetchLinearLayoutManager llm;
private PageSnapWidget pageSnapWidget;
private final SharedPreferences.OnSharedPreferenceChangeListener listener = this::onSharedPreferenceChanged;
private ImageViewerViewModel viewModel;
private int imageIndex = -1; // 0-based image index
private int maxPosition; // For navigation
private int maxPageNumber; // For display; when pages are missing, maxPosition < maxPageNumber
private boolean hasGalleryBeenShown = false;
private final ScrollPositionListener scrollListener = new ScrollPositionListener(this::onScrollPositionChange);
private Disposable slideshowTimer = null;
private Map<String, String> bookPreferences; // Preferences of current book; to feed the book prefs dialog
private boolean isContentArchive; // True if current content is an archive
private Debouncer<Integer> indexRefreshDebouncer;
// Starting index management
private boolean isComputingImageList = false;
private int targetStartingIndex = -1;
// == UI ==
private FragmentViewerPagerBinding binding = null;
private RecyclerView.SmoothScroller smoothScroller;
// Top menu items
private MenuItem showFavoritePagesButton;
private MenuItem shuffleButton;
// Bottom bar controls (proxies for left or right position, depending on current reading direction)
private TextView pageCurrentNumber;
private TextView pageMaxNumber;
@SuppressLint("NonConstantResourceId")
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentViewerPagerBinding.inflate(inflater, container, false);
Preferences.registerPrefsChangedListener(listener);
initPager();
initControlsOverlay();
onUpdateSwipeToFling();
onUpdatePageNumDisplay();
// Top bar controls
binding.controlsOverlay.viewerPagerToolbar.setNavigationOnClickListener(v -> onBackClick());
binding.controlsOverlay.viewerPagerToolbar.setOnMenuItemClickListener(clickedMenuItem -> {
switch (clickedMenuItem.getItemId()) {
case R.id.action_show_favorite_pages:
onShowFavouriteClick();
break;
case R.id.action_page_menu:
onPageMenuClick();
break;
case R.id.action_book_settings:
onBookSettingsClick();
break;
case R.id.action_shuffle:
onShuffleClick();
break;
case R.id.action_slideshow:
startSlideshow();
break;
case R.id.action_delete_book:
ViewerDeleteDialogFragment.invoke(this, !isContentArchive);
break;
default:
// Nothing to do here
}
return true;
});
showFavoritePagesButton = binding.controlsOverlay.viewerPagerToolbar.getMenu().findItem(R.id.action_show_favorite_pages);
shuffleButton = binding.controlsOverlay.viewerPagerToolbar.getMenu().findItem(R.id.action_shuffle);
indexRefreshDebouncer = new Debouncer<>(requireContext(), 75, this::applyStartingIndexInternal);
return binding.getRoot();
}
@Override
public void onDestroyView() {
indexRefreshDebouncer.clear();
binding.recyclerView.setAdapter(null);
binding = null;
super.onDestroyView();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewModelFactory vmFactory = new ViewModelFactory(requireActivity().getApplication());
viewModel = new ViewModelProvider(requireActivity(), vmFactory).get(ImageViewerViewModel.class);
viewModel.onRestoreState(savedInstanceState);
viewModel.getContent()
.observe(getViewLifecycleOwner(), this::onContentChanged);
viewModel.getImages()
.observe(getViewLifecycleOwner(), this::onImagesChanged);
viewModel.getStartingIndex()
.observe(getViewLifecycleOwner(), this::onStartingIndexChanged);
viewModel.getShuffled()
.observe(getViewLifecycleOwner(), this::onShuffleChanged);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_HUD_VISIBLE, binding.controlsOverlay.getRoot().getVisibility());
outState.putBoolean(KEY_SLIDESHOW_ON, (slideshowTimer != null));
outState.putBoolean(KEY_GALLERY_SHOWN, hasGalleryBeenShown);
if (viewModel != null) {
viewModel.setReaderStartingIndex(imageIndex); // Memorize the current page
viewModel.onSaveState(outState);
}
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
int hudVisibility = View.INVISIBLE; // Default state at startup
if (savedInstanceState != null) {
hudVisibility = savedInstanceState.getInt(KEY_HUD_VISIBLE, View.INVISIBLE);
hasGalleryBeenShown = savedInstanceState.getBoolean(KEY_GALLERY_SHOWN, false);
if (savedInstanceState.getBoolean(KEY_SLIDESHOW_ON, false)) startSlideshow(false);
}
binding.controlsOverlay.getRoot().setVisibility(hudVisibility);
}
@Override
public void onStart() {
super.onStart();
((ImageViewerActivity) requireActivity()).registerKeyListener(
new VolumeKeyListener()
.setOnVolumeDownListener(this::previousPage)
.setOnVolumeUpListener(this::nextPage)
.setOnBackListener(this::onBackClick));
}
@Override
public void onResume() {
super.onResume();
setSystemBarsVisible(binding.controlsOverlay.getRoot().getVisibility() == View.VISIBLE); // System bars are visible only if HUD is visible
if (Preferences.Constant.VIEWER_BROWSE_NONE == Preferences.getViewerBrowseMode())
ViewerBrowseModeDialogFragment.invoke(this);
updatePageDisplay();
updateFavouritesGalleryButtonDisplay();
}
// Make sure position is saved when app is closed by the user
@Override
public void onStop() {
viewModel.onLeaveBook(imageIndex);
if (slideshowTimer != null) slideshowTimer.dispose();
((ImageViewerActivity) requireActivity()).unregisterKeyListener();
super.onStop();
}
@Override
public void onDestroy() {
Preferences.unregisterPrefsChangedListener(listener);
if (adapter != null) {
adapter.setRecyclerView(null);
adapter.destroy();
}
super.onDestroy();
}
private void initPager() {
adapter = new ImagePagerAdapter(requireContext());
binding.recyclerView.setAdapter(adapter);
binding.recyclerView.setHasFixedSize(true);
binding.recyclerView.addOnScrollListener(scrollListener);
binding.recyclerView.setOnGetMaxDimensionsListener(this::onGetMaxDimensions);
binding.recyclerView.requestFocus();
binding.recyclerView.setOnScaleListener(scale -> {
if (pageSnapWidget != null && LinearLayoutManager.HORIZONTAL == llm.getOrientation()) {
if (1.0 == scale && !pageSnapWidget.isPageSnapEnabled())
pageSnapWidget.setPageSnapEnabled(true);
else if (1.0 != scale && pageSnapWidget.isPageSnapEnabled())
pageSnapWidget.setPageSnapEnabled(false);
}
});
binding.recyclerView.setLongTapListener(ev -> false);
OnZoneTapListener onHorizontalZoneTapListener = new OnZoneTapListener(binding.recyclerView)
.setOnLeftZoneTapListener(this::onLeftTap)
.setOnRightZoneTapListener(this::onRightTap)
.setOnMiddleZoneTapListener(this::onMiddleTap);
OnZoneTapListener onVerticalZoneTapListener = new OnZoneTapListener(binding.recyclerView)
.setOnMiddleZoneTapListener(this::onMiddleTap);
binding.recyclerView.setTapListener(onVerticalZoneTapListener); // For paper roll mode (vertical)
adapter.setItemTouchListener(onHorizontalZoneTapListener); // For independent images mode (horizontal)
adapter.setRecyclerView(binding.recyclerView);
llm = new PrefetchLinearLayoutManager(getContext());
llm.setExtraLayoutSpace(10);
binding.recyclerView.setLayoutManager(llm);
pageSnapWidget = new PageSnapWidget(binding.recyclerView);
smoothScroller = new LinearSmoothScroller(requireContext()) {
@Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
scrollListener.setOnStartOutOfBoundScrollListener(() -> {
if (Preferences.isViewerContinuous()) previousBook();
});
scrollListener.setOnEndOutOfBoundScrollListener(() -> {
if (Preferences.isViewerContinuous()) nextBook();
});
}
private void initControlsOverlay() {
// Next/previous book
binding.controlsOverlay.viewerPrevBookBtn.setOnClickListener(v -> previousBook());
binding.controlsOverlay.viewerNextBookBtn.setOnClickListener(v -> nextBook());
// Slider and preview
binding.controlsOverlay.viewerSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
binding.controlsOverlay.imagePreviewLeft.setVisibility(View.VISIBLE);
binding.controlsOverlay.imagePreviewCenter.setVisibility(View.VISIBLE);
binding.controlsOverlay.imagePreviewRight.setVisibility(View.VISIBLE);
binding.recyclerView.setVisibility(View.INVISIBLE);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
binding.controlsOverlay.imagePreviewLeft.setVisibility(View.INVISIBLE);
binding.controlsOverlay.imagePreviewCenter.setVisibility(View.INVISIBLE);
binding.controlsOverlay.imagePreviewRight.setVisibility(View.INVISIBLE);
binding.recyclerView.setVisibility(View.VISIBLE);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) seekToPosition(progress);
}
});
// Gallery
binding.controlsOverlay.viewerGalleryBtn.setOnClickListener(v -> displayGallery(false));
binding.controlsOverlay.viewerFavouritesBtn.setOnClickListener(v -> displayGallery(true));
}
/**
* Back button handler
*/
private void onBackClick() {
requireActivity().onBackPressed();
}
/**
* Show the book viewer settings dialog
*/
private void onBookSettingsClick() {
ViewerPrefsDialogFragment.invoke(this, bookPreferences);
}
/**
* Handle click on "Shuffle" action button
*/
private void onShuffleClick() {
goToPage(1);
viewModel.onShuffleClick();
}
/**
* Handle click on "Show favourite pages" action button
*/
private void onShowFavouriteClick() {
viewModel.toggleShowFavouritePages(this::updateShowFavouriteDisplay);
}
/**
* Handle click on "Page menu" action button
*/
private void onPageMenuClick() {
float currentScale = adapter.getScaleAtPosition(imageIndex);
ViewerBottomSheetFragment.show(requireContext(), requireActivity().getSupportFragmentManager(), imageIndex, currentScale);
}
/**
* Observer for changes in the book's list of images
*
* @param images Book's list of images
*/
private void onImagesChanged(List<ImageFile> images) {
isComputingImageList = true;
adapter.submitList(images, this::differEndCallback);
if (images.isEmpty()) {
setSystemBarsVisible(true);
binding.viewerNoImgTxt.setVisibility(View.VISIBLE);
} else {
binding.viewerNoImgTxt.setVisibility(View.GONE);
}
}
/**
* Callback for the end of image list diff calculations
* Activated when all displayed items are placed on their definitive position
*/
private void differEndCallback() {
if (null == binding) return;
maxPosition = adapter.getItemCount() - 1;
binding.controlsOverlay.viewerSeekbar.setMax(maxPosition);
// Can't access the gallery when there's no page to display
if (maxPosition > -1) binding.controlsOverlay.viewerGalleryBtn.setVisibility(View.VISIBLE);
else binding.controlsOverlay.viewerGalleryBtn.setVisibility(View.GONE);
if (targetStartingIndex > -1) applyStartingIndex(targetStartingIndex);
else updatePageDisplay();
isComputingImageList = false;
}
/**
* Observer for changes on the book's starting image index
*
* @param startingIndex Book's starting image index
*/
private void onStartingIndexChanged(Integer startingIndex) {
if (!isComputingImageList) applyStartingIndex(startingIndex);
else targetStartingIndex = startingIndex;
}
private void applyStartingIndex(int startingIndex) {
indexRefreshDebouncer.submit(startingIndex);
targetStartingIndex = -1;
}
private void applyStartingIndexInternal(int startingIndex) {
int currentPosition = Math.max(llm.findFirstVisibleItemPosition(), llm.findFirstCompletelyVisibleItemPosition());
// When target position is the same as current scroll index (0), scrolling is pointless
// -> activate scroll listener manually
if (currentPosition == startingIndex) onScrollPositionChange(startingIndex);
else {
if (LinearLayoutManager.HORIZONTAL == llm.getOrientation() && binding != null)
binding.recyclerView.scrollToPosition(startingIndex);
else
llm.scrollToPositionWithOffset(startingIndex, 0);
}
}
/**
* Observer for changes on the current book
*
* @param content Loaded book
*/
private void onContentChanged(Content content) {
if (null == content) {
onBackClick();
return;
}
bookPreferences = content.getBookPreferences();
isContentArchive = content.isArchive();
onBrowseModeChange(); // TODO check if this can be optimized, as images are loaded twice when a new book is loaded
updateBookNavigation(content);
}
/**
* Observer for changes on the shuffled state
*
* @param isShuffled New shuffled state
*/
private void onShuffleChanged(boolean isShuffled) {
if (isShuffled) {
shuffleButton.setIcon(R.drawable.ic_menu_sort_123);
shuffleButton.setTitle(R.string.viewer_order_123);
} else {
shuffleButton.setIcon(R.drawable.ic_menu_sort_random);
shuffleButton.setTitle(R.string.viewer_order_shuffle);
}
}
@Override
public void onDeleteElement(boolean deletePage) {
if (deletePage)
viewModel.deletePage(imageIndex, this::onDeleteError);
else
viewModel.deleteBook(this::onDeleteError);
}
/**
* Callback for the failure of the "delete item" action
*/
private void onDeleteError(Throwable t) {
Timber.e(t);
if (t instanceof ContentNotRemovedException) {
ContentNotRemovedException e = (ContentNotRemovedException) t;
String message = (null == e.getMessage()) ? "Content removal failed" : e.getMessage();
Snackbar.make(binding.recyclerView, message, BaseTransientBottomBar.LENGTH_LONG).show();
}
}
/**
* Scroll / page change listener
*
* @param scrollPosition New 0-based scroll position
*/
private void onScrollPositionChange(int scrollPosition) {
if (null == binding) return;
if (scrollPosition != imageIndex) {
boolean isScrollLTR = true;
int direction = Preferences.getContentDirection(bookPreferences);
if (Constant.VIEWER_DIRECTION_LTR == direction && imageIndex > scrollPosition)
isScrollLTR = false;
else if (Constant.VIEWER_DIRECTION_RTL == direction && imageIndex < scrollPosition)
isScrollLTR = false;
adapter.setScrollLTR(isScrollLTR);
}
imageIndex = scrollPosition;
ImageFile currentImage = adapter.getImageAt(imageIndex);
if (currentImage != null) viewModel.markPageAsRead(currentImage.getOrder());
// Resets zoom if we're using horizontal (independent pages) mode
if (Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == Preferences.getContentOrientation(bookPreferences))
adapter.resetScaleAtPosition(scrollPosition);
updatePageDisplay();
updateFavouritesGalleryButtonDisplay();
}
/**
* Update the display of page position controls (text and bar)
*/
private void updatePageDisplay() {
ImageFile img = adapter.getImageAt(imageIndex);
if (null == img) {
Timber.w("No image at position %s", imageIndex);
return;
}
String pageNum = img.getOrder() + "";
String maxPage = maxPageNumber + "";
pageCurrentNumber.setText(pageNum);
pageMaxNumber.setText(maxPage);
binding.viewerPagenumberText.setText(format("%s / %s", pageNum, maxPage));
binding.controlsOverlay.viewerSeekbar.setProgress(imageIndex);
}
/**
* Update the visibility of "next/previous book" buttons
*
* @param content Current book
*/
private void updateBookNavigation(@Nonnull Content content) {
if (content.isFirst())
binding.controlsOverlay.viewerPrevBookBtn.setVisibility(View.INVISIBLE);
else binding.controlsOverlay.viewerPrevBookBtn.setVisibility(View.VISIBLE);
if (content.isLast())
binding.controlsOverlay.viewerNextBookBtn.setVisibility(View.INVISIBLE);
else binding.controlsOverlay.viewerNextBookBtn.setVisibility(View.VISIBLE);
maxPageNumber = content.getQtyPages();
updatePageDisplay();
}
/**
* Update the display of the favourites gallery launcher
*/
private void updateFavouritesGalleryButtonDisplay() {
if (binding != null)
if (adapter.isFavouritePresent())
binding.controlsOverlay.viewerFavouritesBtn.setVisibility(View.VISIBLE);
else binding.controlsOverlay.viewerFavouritesBtn.setVisibility(View.INVISIBLE);
}
/**
* Update the display of the "favourite page" action button
*
* @param showFavouritePages True if the button has to represent a favourite page; false instead
*/
private void updateShowFavouriteDisplay(boolean showFavouritePages) {
if (showFavouritePages) {
showFavoritePagesButton.setIcon(R.drawable.ic_filter_favs_on);
showFavoritePagesButton.setTitle(R.string.viewer_filter_favourite_on);
} else {
showFavoritePagesButton.setIcon(R.drawable.ic_filter_favs_off);
showFavoritePagesButton.setTitle(R.string.viewer_filter_favourite_off);
}
}
/**
* Listener for preference changes (from the settings dialog)
*
* @param prefs Shared preferences object
* @param key Key that has been changed
*/
private void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
switch (key) {
case Preferences.Key.VIEWER_BROWSE_MODE:
case Preferences.Key.VIEWER_HOLD_TO_ZOOM:
case Preferences.Key.VIEWER_CONTINUOUS:
onBrowseModeChange();
break;
case Preferences.Key.VIEWER_KEEP_SCREEN_ON:
onUpdatePrefsScreenOn();
break;
case Preferences.Key.VIEWER_ZOOM_TRANSITIONS:
case Preferences.Key.VIEWER_SEPARATING_BARS:
case Preferences.Key.VIEWER_IMAGE_DISPLAY:
case Preferences.Key.VIEWER_AUTO_ROTATE:
case Preferences.Key.VIEWER_RENDERING:
onUpdateImageDisplay();
break;
case Preferences.Key.VIEWER_SWIPE_TO_FLING:
onUpdateSwipeToFling();
break;
case Preferences.Key.VIEWER_DISPLAY_PAGENUM:
onUpdatePageNumDisplay();
break;
default:
// Other changes aren't handled here
}
}
public void onBookPreferenceChanged(@NonNull final Map<String, String> newPrefs) {
viewModel.updateContentPreferences(newPrefs);
}
private void onUpdatePrefsScreenOn() {
if (Preferences.isViewerKeepScreenOn())
requireActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
requireActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void onUpdateSwipeToFling() {
int flingFactor = Preferences.isViewerSwipeToFling() ? 75 : 0;
pageSnapWidget.setFlingSensitivity(flingFactor / 100f);
}
/**
* Re-create and re-bind all Viewholders
*/
private void onUpdateImageDisplay() {
adapter.refreshPrefs(bookPreferences);
binding.recyclerView.setAdapter(null);
binding.recyclerView.setLayoutManager(null);
binding.recyclerView.getRecycledViewPool().clear();
binding.recyclerView.swapAdapter(adapter, false);
binding.recyclerView.setLayoutManager(llm);
adapter.notifyDataSetChanged(); // NB : will re-run onBindViewHolder for all displayed pictures
}
private void onUpdatePageNumDisplay() {
binding.viewerPagenumberText.setVisibility(Preferences.isViewerDisplayPageNum() ? View.VISIBLE : View.GONE);
}
@Override
public void onBrowseModeChange() {
int currentLayoutDirection;
// LinearLayoutManager.setReverseLayout behaves _relatively_ to current Layout Direction
// => need to know that direction before deciding how to set setReverseLayout
if (View.LAYOUT_DIRECTION_LTR == binding.controlsOverlay.getRoot().getLayoutDirection())
currentLayoutDirection = Preferences.Constant.VIEWER_DIRECTION_LTR;
else currentLayoutDirection = Preferences.Constant.VIEWER_DIRECTION_RTL;
llm.setReverseLayout(Preferences.getContentDirection(bookPreferences) != currentLayoutDirection);
int orientation = Preferences.getContentOrientation(bookPreferences);
llm.setOrientation(getOrientation(orientation));
// Resets the views to switch between paper roll mode (vertical) and independent page mode (horizontal)
binding.recyclerView.resetScale();
onUpdateImageDisplay();
if (Preferences.Constant.VIEWER_ORIENTATION_VERTICAL == orientation) {
binding.zoomFrame.enable();
binding.recyclerView.setLongTapZoomEnabled(Preferences.isViewerHoldToZoom());
} else {
binding.zoomFrame.disable();
binding.recyclerView.setLongTapZoomEnabled(!Preferences.isViewerHoldToZoom());
}
pageSnapWidget.setPageSnapEnabled(Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == orientation);
int direction = Preferences.getContentDirection(bookPreferences);
if (Constant.VIEWER_DIRECTION_LTR == direction) {
pageCurrentNumber = binding.controlsOverlay.viewerPagerLeftTxt;
pageMaxNumber = binding.controlsOverlay.viewerPagerRightTxt;
binding.controlsOverlay.viewerSeekbar.setRotationY(0);
} else if (Constant.VIEWER_DIRECTION_RTL == direction) {
pageCurrentNumber = binding.controlsOverlay.viewerPagerRightTxt;
pageMaxNumber = binding.controlsOverlay.viewerPagerLeftTxt;
binding.controlsOverlay.viewerSeekbar.setRotationY(180);
}
pageMaxNumber.setOnClickListener(null);
pageCurrentNumber.setOnClickListener(v -> InputDialog.invokeNumberInputDialog(requireActivity(), R.string.goto_page, this::goToPage));
}
/**
* Transforms current Preferences orientation into LinearLayoutManager orientation code
*
* @return Preferred orientation, as LinearLayoutManager orientation code
*/
private int getOrientation(int orientation) {
if (Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == orientation) {
return LinearLayoutManager.HORIZONTAL;
} else {
return LinearLayoutManager.VERTICAL;
}
}
/**
* Load next page
*/
private void nextPage() {
if (imageIndex == maxPosition) {
if (Preferences.isViewerContinuous()) nextBook();
return;
}
if (Preferences.isViewerTapTransitions()) {
if (Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == Preferences.getContentOrientation(bookPreferences))
binding.recyclerView.smoothScrollToPosition(imageIndex + 1);
else {
smoothScroller.setTargetPosition(imageIndex + 1);
llm.startSmoothScroll(smoothScroller);
}
} else {
if (Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == Preferences.getContentOrientation(bookPreferences))
binding.recyclerView.scrollToPosition(imageIndex + 1);
else
llm.scrollToPositionWithOffset(imageIndex + 1, 0);
}
}
/**
* Load previous page
*/
private void previousPage() {
if (0 == imageIndex) {
if (Preferences.isViewerContinuous()) previousBook();
return;
}
if (Preferences.isViewerTapTransitions())
binding.recyclerView.smoothScrollToPosition(imageIndex - 1);
else
binding.recyclerView.scrollToPosition(imageIndex - 1);
}
/**
* Load next book
*/
private void nextBook() {
viewModel.onLeaveBook(imageIndex);
viewModel.loadNextContent();
}
/**
* Load previous book
*/
private void previousBook() {
viewModel.onLeaveBook(imageIndex);
viewModel.loadPreviousContent();
}
/**
* Seek to the given position; update preview images if they are visible
*
* @param position Position to go to (0-indexed)
*/
private void seekToPosition(int position) {
if (View.VISIBLE == binding.controlsOverlay.imagePreviewCenter.getVisibility()) {
ImageView previousImageView;
ImageView nextImageView;
if (Constant.VIEWER_DIRECTION_LTR == Preferences.getContentDirection(bookPreferences)) {
previousImageView = binding.controlsOverlay.imagePreviewLeft;
nextImageView = binding.controlsOverlay.imagePreviewRight;
} else {
previousImageView = binding.controlsOverlay.imagePreviewRight;
nextImageView = binding.controlsOverlay.imagePreviewLeft;
}
ImageFile previousImg = adapter.getImageAt(position - 1);
ImageFile currentImg = adapter.getImageAt(position);
ImageFile nextImg = adapter.getImageAt(position + 1);
if (previousImg != null) {
Glide.with(previousImageView)
.load(Uri.parse(previousImg.getFileUri()))
.apply(glideRequestOptions)
.into(previousImageView);
previousImageView.setVisibility(View.VISIBLE);
} else previousImageView.setVisibility(View.INVISIBLE);
if (currentImg != null)
Glide.with(binding.controlsOverlay.imagePreviewCenter)
.load(Uri.parse(currentImg.getFileUri()))
.apply(glideRequestOptions)
.into(binding.controlsOverlay.imagePreviewCenter);
if (nextImg != null) {
Glide.with(nextImageView)
.load(Uri.parse(nextImg.getFileUri()))
.apply(glideRequestOptions)
.into(nextImageView);
nextImageView.setVisibility(View.VISIBLE);
} else nextImageView.setVisibility(View.INVISIBLE);
}
if (position == imageIndex + 1 || position == imageIndex - 1) {
binding.recyclerView.smoothScrollToPosition(position);
} else {
binding.recyclerView.scrollToPosition(position);
}
}
/**
* Go to the given page number
*
* @param pageNum Page number to go to (1-indexed)
*/
private void goToPage(int pageNum) {
int position = pageNum - 1;
if (position == imageIndex || position < 0 || position > maxPosition)
return;
seekToPosition(position);
}
/**
* Handler for tapping on the left zone of the screen
*/
private void onLeftTap() {
if (null == binding) return;
// Stop slideshow if it is on
if (slideshowTimer != null) {
stopSlideshow();
return;
}
// Side-tapping disabled when view is zoomed
if (binding.recyclerView.getScale() != 1.0) return;
// Side-tapping disabled when disabled in preferences
if (!Preferences.isViewerTapToTurn()) return;
if (Preferences.Constant.VIEWER_DIRECTION_LTR == Preferences.getContentDirection(bookPreferences))
previousPage();
else
nextPage();
}
/**
* Handler for tapping on the right zone of the screen
*/
private void onRightTap() {
if (null == binding) return;
// Stop slideshow if it is on
if (slideshowTimer != null) {
stopSlideshow();
return;
}
// Side-tapping disabled when view is zoomed
if (binding.recyclerView.getScale() != 1.0) return;
// Side-tapping disabled when disabled in preferences
if (!Preferences.isViewerTapToTurn()) return;
if (Preferences.Constant.VIEWER_DIRECTION_LTR == Preferences.getContentDirection(bookPreferences))
nextPage();
else
previousPage();
}
/**
* Handler for tapping on the middle zone of the screen
*/
private void onMiddleTap() {
if (null == binding) return;
// Stop slideshow if it is on
if (slideshowTimer != null) {
stopSlideshow();
return;
}
if (View.VISIBLE == binding.controlsOverlay.getRoot().getVisibility())
hideControlsOverlay();
else
showControlsOverlay();
}
private void showControlsOverlay() {
binding.controlsOverlay.getRoot().animate()
.alpha(1.0f)
.setDuration(100)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
binding.controlsOverlay.getRoot().setVisibility(View.VISIBLE);
setSystemBarsVisible(true);
}
});
}
private void hideControlsOverlay() {
binding.controlsOverlay.getRoot().animate()
.alpha(0.0f)
.setDuration(100)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
binding.controlsOverlay.getRoot().setVisibility(View.INVISIBLE);
}
});
setSystemBarsVisible(false);
}
/**
* Display the viewer gallery
*
* @param filterFavourites True if only favourite pages have to be shown; false for all pages
*/
private void displayGallery(boolean filterFavourites) {
hasGalleryBeenShown = true;
viewModel.setReaderStartingIndex(imageIndex); // Memorize the current page
if (getParentFragmentManager().getBackStackEntryCount() > 0) { // Gallery mode (Library -> gallery -> pager)
getParentFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); // Leave only the latest element in the back stack
} else { // Pager mode (Library -> pager -> gallery -> pager)
getParentFragmentManager()
.beginTransaction()
.replace(android.R.id.content, ViewerGalleryFragment.newInstance(filterFavourites))
.addToBackStack(null)
.commit();
}
}
/**
* Show / hide bottom and top Android system bars
*
* @param visible True if bars have to be shown; false instead
*/
private void setSystemBarsVisible(boolean visible) {
int uiOptions;
// TODO wait until androidx.core is out of alpha and use WindowCompat (see https://stackoverflow.com/questions/62643517/immersive-fullscreen-on-android-11)
if (visible) {
uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
} else {
uiOptions = View.SYSTEM_UI_FLAG_IMMERSIVE
// Set the content to appear under the system bars so that the
// content doesn't resize when the system bars hide and show.
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// Hide the nav bar and status bar
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
}
// Defensive programming here because crash reports show that getView() sometimes is null
// (just don't ask me why...)
View v = getView();
if (v != null) v.setSystemUiVisibility(uiOptions);
}
private void onGetMaxDimensions(Point maxDimensions) {
adapter.setMaxDimensions(maxDimensions.x, maxDimensions.y);
}
private void startSlideshow() {
startSlideshow(true);
}
private void startSlideshow(boolean showToast) {
// Hide UI
hideControlsOverlay();
// Compute slideshow delay
int delayPref = Preferences.getViewerSlideshowDelay();
int delayMs;
switch (delayPref) {
case Constant.VIEWER_SLIDESHOW_DELAY_05:
delayMs = 500;
break;
case Constant.VIEWER_SLIDESHOW_DELAY_1:
delayMs = 1000;
break;
case Constant.VIEWER_SLIDESHOW_DELAY_4:
delayMs = 4 * 1000;
break;
case Constant.VIEWER_SLIDESHOW_DELAY_8:
delayMs = 8 * 1000;
break;
case Constant.VIEWER_SLIDESHOW_DELAY_16:
delayMs = 16 * 1000;
break;
default:
delayMs = 2 * 1000;
}
if (showToast)
ToastUtil.toast(String.format(Locale.ENGLISH, "Starting slideshow (delay %.1fs)", delayMs / 1000f));
scrollListener.disableScroll();
slideshowTimer = Observable.timer(delayMs, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.computation())
.repeat()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v -> nextPage());
}
private void stopSlideshow() {
if (slideshowTimer != null) {
slideshowTimer.dispose();
slideshowTimer = null;
scrollListener.enableScroll();
ToastUtil.toast("Slideshow stopped");
}
}
}
| app/src/main/java/me/devsaki/hentoid/fragments/viewer/ViewerPagerFragment.java | package me.devsaki.hentoid.fragments.viewer;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.activities.ImageViewerActivity;
import me.devsaki.hentoid.adapters.ImagePagerAdapter;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.databinding.FragmentViewerPagerBinding;
import me.devsaki.hentoid.ui.InputDialog;
import me.devsaki.hentoid.util.Debouncer;
import me.devsaki.hentoid.util.Preferences;
import me.devsaki.hentoid.util.ToastUtil;
import me.devsaki.hentoid.util.exception.ContentNotRemovedException;
import me.devsaki.hentoid.viewmodels.ImageViewerViewModel;
import me.devsaki.hentoid.viewmodels.ViewModelFactory;
import me.devsaki.hentoid.widget.OnZoneTapListener;
import me.devsaki.hentoid.widget.PageSnapWidget;
import me.devsaki.hentoid.widget.PrefetchLinearLayoutManager;
import me.devsaki.hentoid.widget.ScrollPositionListener;
import me.devsaki.hentoid.widget.VolumeKeyListener;
import timber.log.Timber;
import static java.lang.String.format;
import static me.devsaki.hentoid.util.Preferences.Constant;
// TODO : better document and/or encapsulate the difference between
// - paper roll mode (currently used for vertical display)
// - independent page mode (currently used for horizontal display)
public class ViewerPagerFragment extends Fragment implements ViewerBrowseModeDialogFragment.Parent, ViewerPrefsDialogFragment.Parent, ViewerDeleteDialogFragment.Parent {
private static final String KEY_HUD_VISIBLE = "hud_visible";
private static final String KEY_GALLERY_SHOWN = "gallery_shown";
private static final String KEY_SLIDESHOW_ON = "slideshow_on";
private final RequestOptions glideRequestOptions = new RequestOptions().centerInside();
private ImagePagerAdapter adapter;
private PrefetchLinearLayoutManager llm;
private PageSnapWidget pageSnapWidget;
private final SharedPreferences.OnSharedPreferenceChangeListener listener = this::onSharedPreferenceChanged;
private ImageViewerViewModel viewModel;
private int imageIndex = -1; // 0-based image index
private int maxPosition; // For navigation
private int maxPageNumber; // For display; when pages are missing, maxPosition < maxPageNumber
private boolean hasGalleryBeenShown = false;
private final ScrollPositionListener scrollListener = new ScrollPositionListener(this::onScrollPositionChange);
private Disposable slideshowTimer = null;
private Map<String, String> bookPreferences; // Preferences of current book; to feed the book prefs dialog
private boolean isContentArchive; // True if current content is an archive
private Debouncer<Integer> indexRefreshDebouncer;
// Starting index management
private boolean isComputingImageList = false;
private int targetStartingIndex = -1;
// == UI ==
private FragmentViewerPagerBinding binding = null;
private RecyclerView.SmoothScroller smoothScroller;
// Top menu items
private MenuItem showFavoritePagesButton;
private MenuItem shuffleButton;
// Bottom bar controls (proxies for left or right position, depending on current reading direction)
private TextView pageCurrentNumber;
private TextView pageMaxNumber;
@SuppressLint("NonConstantResourceId")
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentViewerPagerBinding.inflate(inflater, container, false);
Preferences.registerPrefsChangedListener(listener);
initPager();
initControlsOverlay();
onUpdateSwipeToFling();
onUpdatePageNumDisplay();
// Top bar controls
binding.controlsOverlay.viewerPagerToolbar.setNavigationOnClickListener(v -> onBackClick());
binding.controlsOverlay.viewerPagerToolbar.setOnMenuItemClickListener(clickedMenuItem -> {
switch (clickedMenuItem.getItemId()) {
case R.id.action_show_favorite_pages:
onShowFavouriteClick();
break;
case R.id.action_page_menu:
onPageMenuClick();
break;
case R.id.action_book_settings:
onBookSettingsClick();
break;
case R.id.action_shuffle:
onShuffleClick();
break;
case R.id.action_slideshow:
startSlideshow();
break;
case R.id.action_delete_book:
ViewerDeleteDialogFragment.invoke(this, !isContentArchive);
break;
default:
// Nothing to do here
}
return true;
});
showFavoritePagesButton = binding.controlsOverlay.viewerPagerToolbar.getMenu().findItem(R.id.action_show_favorite_pages);
shuffleButton = binding.controlsOverlay.viewerPagerToolbar.getMenu().findItem(R.id.action_shuffle);
indexRefreshDebouncer = new Debouncer<>(requireContext(), 75, this::applyStartingIndexInternal);
return binding.getRoot();
}
@Override
public void onDestroyView() {
indexRefreshDebouncer.clear();
binding.recyclerView.setAdapter(null);
binding = null;
super.onDestroyView();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewModelFactory vmFactory = new ViewModelFactory(requireActivity().getApplication());
viewModel = new ViewModelProvider(requireActivity(), vmFactory).get(ImageViewerViewModel.class);
viewModel.onRestoreState(savedInstanceState);
viewModel.getContent()
.observe(getViewLifecycleOwner(), this::onContentChanged);
viewModel.getImages()
.observe(getViewLifecycleOwner(), this::onImagesChanged);
viewModel.getStartingIndex()
.observe(getViewLifecycleOwner(), this::onStartingIndexChanged);
viewModel.getShuffled()
.observe(getViewLifecycleOwner(), this::onShuffleChanged);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_HUD_VISIBLE, binding.controlsOverlay.getRoot().getVisibility());
outState.putBoolean(KEY_SLIDESHOW_ON, (slideshowTimer != null));
outState.putBoolean(KEY_GALLERY_SHOWN, hasGalleryBeenShown);
if (viewModel != null) {
viewModel.setReaderStartingIndex(imageIndex); // Memorize the current page
viewModel.onSaveState(outState);
}
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
int hudVisibility = View.INVISIBLE; // Default state at startup
if (savedInstanceState != null) {
hudVisibility = savedInstanceState.getInt(KEY_HUD_VISIBLE, View.INVISIBLE);
hasGalleryBeenShown = savedInstanceState.getBoolean(KEY_GALLERY_SHOWN, false);
if (savedInstanceState.getBoolean(KEY_SLIDESHOW_ON, false)) startSlideshow(false);
}
binding.controlsOverlay.getRoot().setVisibility(hudVisibility);
}
@Override
public void onStart() {
super.onStart();
((ImageViewerActivity) requireActivity()).registerKeyListener(
new VolumeKeyListener()
.setOnVolumeDownListener(this::previousPage)
.setOnVolumeUpListener(this::nextPage)
.setOnBackListener(this::onBackClick));
}
@Override
public void onResume() {
super.onResume();
setSystemBarsVisible(binding.controlsOverlay.getRoot().getVisibility() == View.VISIBLE); // System bars are visible only if HUD is visible
if (Preferences.Constant.VIEWER_BROWSE_NONE == Preferences.getViewerBrowseMode())
ViewerBrowseModeDialogFragment.invoke(this);
updatePageDisplay();
updateFavouritesGalleryButtonDisplay();
}
// Make sure position is saved when app is closed by the user
@Override
public void onStop() {
viewModel.onLeaveBook(imageIndex);
if (slideshowTimer != null) slideshowTimer.dispose();
((ImageViewerActivity) requireActivity()).unregisterKeyListener();
super.onStop();
}
@Override
public void onDestroy() {
Preferences.unregisterPrefsChangedListener(listener);
if (adapter != null) {
adapter.setRecyclerView(null);
adapter.destroy();
}
super.onDestroy();
}
private void initPager() {
adapter = new ImagePagerAdapter(requireContext());
binding.recyclerView.setAdapter(adapter);
binding.recyclerView.setHasFixedSize(true);
binding.recyclerView.addOnScrollListener(scrollListener);
binding.recyclerView.setOnGetMaxDimensionsListener(this::onGetMaxDimensions);
binding.recyclerView.requestFocus();
binding.recyclerView.setOnScaleListener(scale -> {
if (pageSnapWidget != null && LinearLayoutManager.HORIZONTAL == llm.getOrientation()) {
if (1.0 == scale && !pageSnapWidget.isPageSnapEnabled())
pageSnapWidget.setPageSnapEnabled(true);
else if (1.0 != scale && pageSnapWidget.isPageSnapEnabled())
pageSnapWidget.setPageSnapEnabled(false);
}
});
binding.recyclerView.setLongTapListener(ev -> false);
OnZoneTapListener onHorizontalZoneTapListener = new OnZoneTapListener(binding.recyclerView)
.setOnLeftZoneTapListener(this::onLeftTap)
.setOnRightZoneTapListener(this::onRightTap)
.setOnMiddleZoneTapListener(this::onMiddleTap);
OnZoneTapListener onVerticalZoneTapListener = new OnZoneTapListener(binding.recyclerView)
.setOnMiddleZoneTapListener(this::onMiddleTap);
binding.recyclerView.setTapListener(onVerticalZoneTapListener); // For paper roll mode (vertical)
adapter.setItemTouchListener(onHorizontalZoneTapListener); // For independent images mode (horizontal)
adapter.setRecyclerView(binding.recyclerView);
llm = new PrefetchLinearLayoutManager(getContext());
llm.setExtraLayoutSpace(10);
binding.recyclerView.setLayoutManager(llm);
pageSnapWidget = new PageSnapWidget(binding.recyclerView);
smoothScroller = new LinearSmoothScroller(requireContext()) {
@Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
scrollListener.setOnStartOutOfBoundScrollListener(() -> {
if (Preferences.isViewerContinuous()) previousBook();
});
scrollListener.setOnEndOutOfBoundScrollListener(() -> {
if (Preferences.isViewerContinuous()) nextBook();
});
}
private void initControlsOverlay() {
// Next/previous book
binding.controlsOverlay.viewerPrevBookBtn.setOnClickListener(v -> previousBook());
binding.controlsOverlay.viewerNextBookBtn.setOnClickListener(v -> nextBook());
// Slider and preview
binding.controlsOverlay.viewerSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
binding.controlsOverlay.imagePreviewLeft.setVisibility(View.VISIBLE);
binding.controlsOverlay.imagePreviewCenter.setVisibility(View.VISIBLE);
binding.controlsOverlay.imagePreviewRight.setVisibility(View.VISIBLE);
binding.recyclerView.setVisibility(View.INVISIBLE);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
binding.controlsOverlay.imagePreviewLeft.setVisibility(View.INVISIBLE);
binding.controlsOverlay.imagePreviewCenter.setVisibility(View.INVISIBLE);
binding.controlsOverlay.imagePreviewRight.setVisibility(View.INVISIBLE);
binding.recyclerView.setVisibility(View.VISIBLE);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) seekToPosition(progress);
}
});
// Gallery
binding.controlsOverlay.viewerGalleryBtn.setOnClickListener(v -> displayGallery(false));
binding.controlsOverlay.viewerFavouritesBtn.setOnClickListener(v -> displayGallery(true));
}
/**
* Back button handler
*/
private void onBackClick() {
requireActivity().onBackPressed();
}
/**
* Show the book viewer settings dialog
*/
private void onBookSettingsClick() {
ViewerPrefsDialogFragment.invoke(this, bookPreferences);
}
/**
* Handle click on "Shuffle" action button
*/
private void onShuffleClick() {
goToPage(1);
viewModel.onShuffleClick();
}
/**
* Handle click on "Show favourite pages" action button
*/
private void onShowFavouriteClick() {
viewModel.toggleShowFavouritePages(this::updateShowFavouriteDisplay);
}
/**
* Handle click on "Page menu" action button
*/
private void onPageMenuClick() {
float currentScale = adapter.getScaleAtPosition(imageIndex);
ViewerBottomSheetFragment.show(requireContext(), requireActivity().getSupportFragmentManager(), imageIndex, currentScale);
}
/**
* Observer for changes in the book's list of images
*
* @param images Book's list of images
*/
private void onImagesChanged(List<ImageFile> images) {
isComputingImageList = true;
adapter.submitList(images, this::differEndCallback);
if (images.isEmpty()) {
setSystemBarsVisible(true);
binding.viewerNoImgTxt.setVisibility(View.VISIBLE);
} else {
binding.viewerNoImgTxt.setVisibility(View.GONE);
}
}
/**
* Callback for the end of image list diff calculations
* Activated when all displayed items are placed on their definitive position
*/
private void differEndCallback() {
if (null == binding) return;
maxPosition = adapter.getItemCount() - 1;
binding.controlsOverlay.viewerSeekbar.setMax(maxPosition);
// Can't access the gallery when there's no page to display
if (maxPosition > -1) binding.controlsOverlay.viewerGalleryBtn.setVisibility(View.VISIBLE);
else binding.controlsOverlay.viewerGalleryBtn.setVisibility(View.GONE);
if (targetStartingIndex > -1) applyStartingIndex(targetStartingIndex);
else updatePageDisplay();
isComputingImageList = false;
}
/**
* Observer for changes on the book's starting image index
*
* @param startingIndex Book's starting image index
*/
private void onStartingIndexChanged(Integer startingIndex) {
if (!isComputingImageList) applyStartingIndex(startingIndex);
else targetStartingIndex = startingIndex;
}
private void applyStartingIndex(int startingIndex) {
indexRefreshDebouncer.submit(startingIndex);
targetStartingIndex = -1;
}
private void applyStartingIndexInternal(int startingIndex) {
int currentPosition = Math.max(llm.findFirstVisibleItemPosition(), llm.findFirstCompletelyVisibleItemPosition());
// When target position is the same as current scroll index (0), scrolling is pointless
// -> activate scroll listener manually
if (currentPosition == startingIndex) onScrollPositionChange(startingIndex);
else {
if (LinearLayoutManager.HORIZONTAL == llm.getOrientation() && binding != null)
binding.recyclerView.scrollToPosition(startingIndex);
else
llm.scrollToPositionWithOffset(startingIndex, 0);
}
}
/**
* Observer for changes on the current book
*
* @param content Loaded book
*/
private void onContentChanged(Content content) {
if (null == content) {
onBackClick();
return;
}
bookPreferences = content.getBookPreferences();
isContentArchive = content.isArchive();
onBrowseModeChange(); // TODO check if this can be optimized, as images are loaded twice when a new book is loaded
updateBookNavigation(content);
}
/**
* Observer for changes on the shuffled state
*
* @param isShuffled New shuffled state
*/
private void onShuffleChanged(boolean isShuffled) {
if (isShuffled) {
shuffleButton.setIcon(R.drawable.ic_menu_sort_123);
shuffleButton.setTitle(R.string.viewer_order_123);
} else {
shuffleButton.setIcon(R.drawable.ic_menu_sort_random);
shuffleButton.setTitle(R.string.viewer_order_shuffle);
}
}
@Override
public void onDeleteElement(boolean deletePage) {
if (deletePage)
viewModel.deletePage(imageIndex, this::onDeleteError);
else
viewModel.deleteBook(this::onDeleteError);
}
/**
* Callback for the failure of the "delete item" action
*/
private void onDeleteError(Throwable t) {
Timber.e(t);
if (t instanceof ContentNotRemovedException) {
ContentNotRemovedException e = (ContentNotRemovedException) t;
String message = (null == e.getMessage()) ? "Content removal failed" : e.getMessage();
Snackbar.make(binding.recyclerView, message, BaseTransientBottomBar.LENGTH_LONG).show();
}
}
/**
* Scroll / page change listener
*
* @param scrollPosition New 0-based scroll position
*/
private void onScrollPositionChange(int scrollPosition) {
if (null == binding) return;
if (scrollPosition != imageIndex) {
boolean isScrollLTR = true;
int direction = Preferences.getContentDirection(bookPreferences);
if (Constant.VIEWER_DIRECTION_LTR == direction && imageIndex > scrollPosition)
isScrollLTR = false;
else if (Constant.VIEWER_DIRECTION_RTL == direction && imageIndex < scrollPosition)
isScrollLTR = false;
adapter.setScrollLTR(isScrollLTR);
}
imageIndex = scrollPosition;
ImageFile currentImage = adapter.getImageAt(imageIndex);
if (currentImage != null) viewModel.markPageAsRead(currentImage.getOrder());
// Resets zoom if we're using horizontal (independent pages) mode
if (Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == Preferences.getContentOrientation(bookPreferences))
adapter.resetScaleAtPosition(scrollPosition);
updatePageDisplay();
updateFavouritesGalleryButtonDisplay();
}
/**
* Update the display of page position controls (text and bar)
*/
private void updatePageDisplay() {
ImageFile img = adapter.getImageAt(imageIndex);
if (null == img) {
Timber.w("No image at position %s", imageIndex);
return;
}
String pageNum = img.getOrder() + "";
String maxPage = maxPageNumber + "";
pageCurrentNumber.setText(pageNum);
pageMaxNumber.setText(maxPage);
binding.viewerPagenumberText.setText(format("%s / %s", pageNum, maxPage));
binding.controlsOverlay.viewerSeekbar.setProgress(imageIndex);
}
/**
* Update the visibility of "next/previous book" buttons
*
* @param content Current book
*/
private void updateBookNavigation(@Nonnull Content content) {
if (content.isFirst())
binding.controlsOverlay.viewerPrevBookBtn.setVisibility(View.INVISIBLE);
else binding.controlsOverlay.viewerPrevBookBtn.setVisibility(View.VISIBLE);
if (content.isLast())
binding.controlsOverlay.viewerNextBookBtn.setVisibility(View.INVISIBLE);
else binding.controlsOverlay.viewerNextBookBtn.setVisibility(View.VISIBLE);
maxPageNumber = content.getQtyPages();
updatePageDisplay();
}
/**
* Update the display of the favourites gallery launcher
*/
private void updateFavouritesGalleryButtonDisplay() {
if (binding != null)
if (adapter.isFavouritePresent())
binding.controlsOverlay.viewerFavouritesBtn.setVisibility(View.VISIBLE);
else binding.controlsOverlay.viewerFavouritesBtn.setVisibility(View.INVISIBLE);
}
/**
* Update the display of the "favourite page" action button
*
* @param showFavouritePages True if the button has to represent a favourite page; false instead
*/
private void updateShowFavouriteDisplay(boolean showFavouritePages) {
if (showFavouritePages) {
showFavoritePagesButton.setIcon(R.drawable.ic_filter_favs_on);
showFavoritePagesButton.setTitle(R.string.viewer_filter_favourite_on);
} else {
showFavoritePagesButton.setIcon(R.drawable.ic_filter_favs_off);
showFavoritePagesButton.setTitle(R.string.viewer_filter_favourite_off);
}
}
/**
* Listener for preference changes (from the settings dialog)
*
* @param prefs Shared preferences object
* @param key Key that has been changed
*/
private void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
switch (key) {
case Preferences.Key.VIEWER_BROWSE_MODE:
case Preferences.Key.VIEWER_HOLD_TO_ZOOM:
case Preferences.Key.VIEWER_CONTINUOUS:
onBrowseModeChange();
break;
case Preferences.Key.VIEWER_KEEP_SCREEN_ON:
onUpdatePrefsScreenOn();
break;
case Preferences.Key.VIEWER_ZOOM_TRANSITIONS:
case Preferences.Key.VIEWER_SEPARATING_BARS:
case Preferences.Key.VIEWER_IMAGE_DISPLAY:
case Preferences.Key.VIEWER_AUTO_ROTATE:
case Preferences.Key.VIEWER_RENDERING:
onUpdateImageDisplay();
break;
case Preferences.Key.VIEWER_SWIPE_TO_FLING:
onUpdateSwipeToFling();
break;
case Preferences.Key.VIEWER_DISPLAY_PAGENUM:
onUpdatePageNumDisplay();
break;
default:
// Other changes aren't handled here
}
}
public void onBookPreferenceChanged(@NonNull final Map<String, String> newPrefs) {
viewModel.updateContentPreferences(newPrefs);
}
private void onUpdatePrefsScreenOn() {
if (Preferences.isViewerKeepScreenOn())
requireActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
requireActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void onUpdateSwipeToFling() {
int flingFactor = Preferences.isViewerSwipeToFling() ? 75 : 0;
pageSnapWidget.setFlingSensitivity(flingFactor / 100f);
}
/**
* Re-create and re-bind all Viewholders
*/
private void onUpdateImageDisplay() {
adapter.refreshPrefs(bookPreferences);
binding.recyclerView.setAdapter(null);
binding.recyclerView.setLayoutManager(null);
binding.recyclerView.getRecycledViewPool().clear();
binding.recyclerView.swapAdapter(adapter, false);
binding.recyclerView.setLayoutManager(llm);
adapter.notifyDataSetChanged(); // NB : will re-run onBindViewHolder for all displayed pictures
}
private void onUpdatePageNumDisplay() {
binding.viewerPagenumberText.setVisibility(Preferences.isViewerDisplayPageNum() ? View.VISIBLE : View.GONE);
}
@Override
public void onBrowseModeChange() {
int currentLayoutDirection;
// LinearLayoutManager.setReverseLayout behaves _relatively_ to current Layout Direction
// => need to know that direction before deciding how to set setReverseLayout
if (View.LAYOUT_DIRECTION_LTR == binding.controlsOverlay.getRoot().getLayoutDirection())
currentLayoutDirection = Preferences.Constant.VIEWER_DIRECTION_LTR;
else currentLayoutDirection = Preferences.Constant.VIEWER_DIRECTION_RTL;
llm.setReverseLayout(Preferences.getContentDirection(bookPreferences) != currentLayoutDirection);
int orientation = Preferences.getContentOrientation(bookPreferences);
llm.setOrientation(getOrientation(orientation));
// Resets the views to switch between paper roll mode (vertical) and independent page mode (horizontal)
binding.recyclerView.resetScale();
onUpdateImageDisplay();
if (Preferences.Constant.VIEWER_ORIENTATION_VERTICAL == orientation) {
binding.zoomFrame.enable();
binding.recyclerView.setLongTapZoomEnabled(Preferences.isViewerHoldToZoom());
} else {
binding.zoomFrame.disable();
binding.recyclerView.setLongTapZoomEnabled(!Preferences.isViewerHoldToZoom());
}
pageSnapWidget.setPageSnapEnabled(Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == orientation);
int direction = Preferences.getContentDirection(bookPreferences);
if (Constant.VIEWER_DIRECTION_LTR == direction) {
pageCurrentNumber = binding.controlsOverlay.viewerPagerLeftTxt;
pageMaxNumber = binding.controlsOverlay.viewerPagerRightTxt;
binding.controlsOverlay.viewerSeekbar.setRotationY(0);
} else if (Constant.VIEWER_DIRECTION_RTL == direction) {
pageCurrentNumber = binding.controlsOverlay.viewerPagerRightTxt;
pageMaxNumber = binding.controlsOverlay.viewerPagerLeftTxt;
binding.controlsOverlay.viewerSeekbar.setRotationY(180);
}
pageMaxNumber.setOnClickListener(null);
pageCurrentNumber.setOnClickListener(v -> InputDialog.invokeNumberInputDialog(requireActivity(), R.string.goto_page, this::goToPage));
}
/**
* Transforms current Preferences orientation into LinearLayoutManager orientation code
*
* @return Preferred orientation, as LinearLayoutManager orientation code
*/
private int getOrientation(int orientation) {
if (Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == orientation) {
return LinearLayoutManager.HORIZONTAL;
} else {
return LinearLayoutManager.VERTICAL;
}
}
/**
* Load next page
*/
private void nextPage() {
if (imageIndex == maxPosition) {
if (Preferences.isViewerContinuous()) nextBook();
return;
}
if (Preferences.isViewerTapTransitions()) {
if (Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == Preferences.getContentOrientation(bookPreferences))
binding.recyclerView.smoothScrollToPosition(imageIndex + 1);
else {
smoothScroller.setTargetPosition(imageIndex + 1);
llm.startSmoothScroll(smoothScroller);
}
} else {
if (Preferences.Constant.VIEWER_ORIENTATION_HORIZONTAL == Preferences.getContentOrientation(bookPreferences))
binding.recyclerView.scrollToPosition(imageIndex + 1);
else
llm.scrollToPositionWithOffset(imageIndex + 1, 0);
}
}
/**
* Load previous page
*/
private void previousPage() {
if (0 == imageIndex) {
if (Preferences.isViewerContinuous()) previousBook();
return;
}
if (Preferences.isViewerTapTransitions())
binding.recyclerView.smoothScrollToPosition(imageIndex - 1);
else
binding.recyclerView.scrollToPosition(imageIndex - 1);
}
/**
* Load next book
*/
private void nextBook() {
viewModel.onLeaveBook(imageIndex);
viewModel.loadNextContent();
}
/**
* Load previous book
*/
private void previousBook() {
viewModel.onLeaveBook(imageIndex);
viewModel.loadPreviousContent();
}
/**
* Seek to the given position; update preview images if they are visible
*
* @param position Position to go to (0-indexed)
*/
private void seekToPosition(int position) {
if (View.VISIBLE == binding.controlsOverlay.imagePreviewCenter.getVisibility()) {
ImageView previousImageView;
ImageView nextImageView;
if (Constant.VIEWER_DIRECTION_LTR == Preferences.getContentDirection(bookPreferences)) {
previousImageView = binding.controlsOverlay.imagePreviewLeft;
nextImageView = binding.controlsOverlay.imagePreviewRight;
} else {
previousImageView = binding.controlsOverlay.imagePreviewRight;
nextImageView = binding.controlsOverlay.imagePreviewLeft;
}
ImageFile previousImg = adapter.getImageAt(position - 1);
ImageFile currentImg = adapter.getImageAt(position);
ImageFile nextImg = adapter.getImageAt(position + 1);
if (previousImg != null) {
Glide.with(previousImageView)
.load(Uri.parse(previousImg.getFileUri()))
.apply(glideRequestOptions)
.into(previousImageView);
previousImageView.setVisibility(View.VISIBLE);
} else previousImageView.setVisibility(View.INVISIBLE);
if (currentImg != null)
Glide.with(binding.controlsOverlay.imagePreviewCenter)
.load(Uri.parse(currentImg.getFileUri()))
.apply(glideRequestOptions)
.into(binding.controlsOverlay.imagePreviewCenter);
if (nextImg != null) {
Glide.with(nextImageView)
.load(Uri.parse(nextImg.getFileUri()))
.apply(glideRequestOptions)
.into(nextImageView);
nextImageView.setVisibility(View.VISIBLE);
} else nextImageView.setVisibility(View.INVISIBLE);
}
if (position == imageIndex + 1 || position == imageIndex - 1) {
binding.recyclerView.smoothScrollToPosition(position);
} else {
binding.recyclerView.scrollToPosition(position);
}
}
/**
* Go to the given page number
*
* @param pageNum Page number to go to (1-indexed)
*/
private void goToPage(int pageNum) {
int position = pageNum - 1;
if (position == imageIndex || position < 0 || position > maxPosition)
return;
seekToPosition(position);
}
/**
* Handler for tapping on the left zone of the screen
*/
private void onLeftTap() {
// Stop slideshow if it is on
if (slideshowTimer != null) {
stopSlideshow();
return;
}
// Side-tapping disabled when view is zoomed
if (binding.recyclerView.getScale() != 1.0) return;
// Side-tapping disabled when disabled in preferences
if (!Preferences.isViewerTapToTurn()) return;
if (Preferences.Constant.VIEWER_DIRECTION_LTR == Preferences.getContentDirection(bookPreferences))
previousPage();
else
nextPage();
}
/**
* Handler for tapping on the right zone of the screen
*/
private void onRightTap() {
// Stop slideshow if it is on
if (slideshowTimer != null) {
stopSlideshow();
return;
}
// Side-tapping disabled when view is zoomed
if (binding.recyclerView.getScale() != 1.0) return;
// Side-tapping disabled when disabled in preferences
if (!Preferences.isViewerTapToTurn()) return;
if (Preferences.Constant.VIEWER_DIRECTION_LTR == Preferences.getContentDirection(bookPreferences))
nextPage();
else
previousPage();
}
/**
* Handler for tapping on the middle zone of the screen
*/
private void onMiddleTap() {
// Stop slideshow if it is on
if (slideshowTimer != null) {
stopSlideshow();
return;
}
if (View.VISIBLE == binding.controlsOverlay.getRoot().getVisibility())
hideControlsOverlay();
else
showControlsOverlay();
}
private void showControlsOverlay() {
binding.controlsOverlay.getRoot().animate()
.alpha(1.0f)
.setDuration(100)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
binding.controlsOverlay.getRoot().setVisibility(View.VISIBLE);
setSystemBarsVisible(true);
}
});
}
private void hideControlsOverlay() {
binding.controlsOverlay.getRoot().animate()
.alpha(0.0f)
.setDuration(100)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
binding.controlsOverlay.getRoot().setVisibility(View.INVISIBLE);
}
});
setSystemBarsVisible(false);
}
/**
* Display the viewer gallery
*
* @param filterFavourites True if only favourite pages have to be shown; false for all pages
*/
private void displayGallery(boolean filterFavourites) {
hasGalleryBeenShown = true;
viewModel.setReaderStartingIndex(imageIndex); // Memorize the current page
if (getParentFragmentManager().getBackStackEntryCount() > 0) { // Gallery mode (Library -> gallery -> pager)
getParentFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); // Leave only the latest element in the back stack
} else { // Pager mode (Library -> pager -> gallery -> pager)
getParentFragmentManager()
.beginTransaction()
.replace(android.R.id.content, ViewerGalleryFragment.newInstance(filterFavourites))
.addToBackStack(null)
.commit();
}
}
/**
* Show / hide bottom and top Android system bars
*
* @param visible True if bars have to be shown; false instead
*/
private void setSystemBarsVisible(boolean visible) {
int uiOptions;
// TODO wait until androidx.core is out of alpha and use WindowCompat (see https://stackoverflow.com/questions/62643517/immersive-fullscreen-on-android-11)
if (visible) {
uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
} else {
uiOptions = View.SYSTEM_UI_FLAG_IMMERSIVE
// Set the content to appear under the system bars so that the
// content doesn't resize when the system bars hide and show.
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// Hide the nav bar and status bar
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
}
// Defensive programming here because crash reports show that getView() sometimes is null
// (just don't ask me why...)
View v = getView();
if (v != null) v.setSystemUiVisibility(uiOptions);
}
private void onGetMaxDimensions(Point maxDimensions) {
adapter.setMaxDimensions(maxDimensions.x, maxDimensions.y);
}
private void startSlideshow() {
startSlideshow(true);
}
private void startSlideshow(boolean showToast) {
// Hide UI
hideControlsOverlay();
// Compute slideshow delay
int delayPref = Preferences.getViewerSlideshowDelay();
int delayMs;
switch (delayPref) {
case Constant.VIEWER_SLIDESHOW_DELAY_05:
delayMs = 500;
break;
case Constant.VIEWER_SLIDESHOW_DELAY_1:
delayMs = 1000;
break;
case Constant.VIEWER_SLIDESHOW_DELAY_4:
delayMs = 4 * 1000;
break;
case Constant.VIEWER_SLIDESHOW_DELAY_8:
delayMs = 8 * 1000;
break;
case Constant.VIEWER_SLIDESHOW_DELAY_16:
delayMs = 16 * 1000;
break;
default:
delayMs = 2 * 1000;
}
if (showToast)
ToastUtil.toast(String.format(Locale.ENGLISH, "Starting slideshow (delay %.1fs)", delayMs / 1000f));
scrollListener.disableScroll();
slideshowTimer = Observable.timer(delayMs, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.computation())
.repeat()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v -> nextPage());
}
private void stopSlideshow() {
if (slideshowTimer != null) {
slideshowTimer.dispose();
slideshowTimer = null;
scrollListener.enableScroll();
ToastUtil.toast("Slideshow stopped");
}
}
}
| Fix NPE
| app/src/main/java/me/devsaki/hentoid/fragments/viewer/ViewerPagerFragment.java | Fix NPE |
|
Java | apache-2.0 | 1d3cb7b1814fa748ed7ef9ccd7d2f5789c4bf33c | 0 | binarygu/Metamorphosis,githubcolin/Metamorphosis,fogu/Metamorphosis,killme2008/Metamorphosis,jarvisxiong/Metamorphosis,fogu/Metamorphosis,ronaldo9grey/Metamorphosis,yuzhu712/Metamorphosis,makemyownlife/Metamorphosis,xiaojiaqi/Metamorphosis,fengshao0907/Metamorphosis,makemyownlife/Metamorphosis,ronaldo9grey/Metamorphosis,makemyownlife/Metamorphosis,fengshao0907/Metamorphosis,IBYoung/Metamorphosis,githubcolin/Metamorphosis,fogu/Metamorphosis,yuzhu712/Metamorphosis,xiaojiaqi/Metamorphosis,makemyownlife/Metamorphosis,fool-persen/Metamorphosis,jarvisxiong/Metamorphosis,ronaldo9grey/Metamorphosis,jarvisxiong/Metamorphosis,IBYoung/Metamorphosis,fool-persen/Metamorphosis,fool-persen/Metamorphosis,githubcolin/Metamorphosis,jarvisxiong/Metamorphosis,IBYoung/Metamorphosis,fool-persen/Metamorphosis,killme2008/Metamorphosis,jarvisxiong/Metamorphosis,fogu/Metamorphosis,fengshao0907/Metamorphosis,fengshao0907/Metamorphosis,binarygu/Metamorphosis,binarygu/Metamorphosis,binarygu/Metamorphosis,binarygu/Metamorphosis,272029252/Metamorphosis,272029252/Metamorphosis,fool-persen/Metamorphosis,githubcolin/Metamorphosis,xiaojiaqi/Metamorphosis,ronaldo9grey/Metamorphosis,xiaojiaqi/Metamorphosis,fogu/Metamorphosis,jarvisxiong/Metamorphosis,yuzhu712/Metamorphosis,IBYoung/Metamorphosis,ronaldo9grey/Metamorphosis,binarygu/Metamorphosis,IBYoung/Metamorphosis,yuzhu712/Metamorphosis,xiaojiaqi/Metamorphosis,killme2008/Metamorphosis,killme2008/Metamorphosis,fengshao0907/Metamorphosis,yuzhu712/Metamorphosis,272029252/Metamorphosis,yuzhu712/Metamorphosis,githubcolin/Metamorphosis,272029252/Metamorphosis,ronaldo9grey/Metamorphosis,githubcolin/Metamorphosis,killme2008/Metamorphosis,272029252/Metamorphosis,IBYoung/Metamorphosis,makemyownlife/Metamorphosis,272029252/Metamorphosis,fengshao0907/Metamorphosis,killme2008/Metamorphosis,fogu/Metamorphosis,fool-persen/Metamorphosis,makemyownlife/Metamorphosis,xiaojiaqi/Metamorphosis | /*
* (C) 2007-2012 Alibaba Group Holding Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Authors:
* wuhua <[email protected]> , boyan <[email protected]>
*/
package com.taobao.metamorphosis.client.producer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.taobao.gecko.service.exception.NotifyRemotingException;
import com.taobao.metamorphosis.Message;
import com.taobao.metamorphosis.client.MetaClientConfig;
import com.taobao.metamorphosis.client.RemotingClientWrapper;
import com.taobao.metamorphosis.client.ZkClientChangedListener;
import com.taobao.metamorphosis.cluster.Partition;
import com.taobao.metamorphosis.exception.MetaClientException;
import com.taobao.metamorphosis.utils.MetaZookeeper;
import com.taobao.metamorphosis.utils.ZkUtils;
/**
* ProducerzkĽ
*
* @author boyan
* @Date 2011-4-26
*/
public class ProducerZooKeeper implements ZkClientChangedListener {
private final RemotingClientWrapper remotingClient;
private final ConcurrentHashMap<String, FutureTask<BrokerConnectionListener>> topicConnectionListeners =
new ConcurrentHashMap<String, FutureTask<BrokerConnectionListener>>();
private final MetaClientConfig metaClientConfig;
private ZkClient zkClient;
private final MetaZookeeper metaZookeeper;
/**
* Ĭtopicҷûҵ÷ʱ��͵topicµbroker
*/
private String defaultTopic;
static final Log log = LogFactory.getLog(ProducerZooKeeper.class);
public static class BrokersInfo {
final Map<Integer/* broker id */, String/* server url */> oldBrokerStringMap;
final Map<String/* topic */, List<Partition>/* partition list */> oldTopicPartitionMap;
public BrokersInfo(final Map<Integer, String> oldBrokerStringMap,
final Map<String, List<Partition>> oldTopicPartitionMap) {
super();
this.oldBrokerStringMap = oldBrokerStringMap;
this.oldTopicPartitionMap = oldTopicPartitionMap;
}
}
final class BrokerConnectionListener implements IZkChildListener {
final Lock lock = new ReentrantLock();
volatile BrokersInfo brokersInfo = new BrokersInfo(new TreeMap<Integer, String>(),
new HashMap<String, List<Partition>>());
final String topic;
final Set<Object> references = Collections.synchronizedSet(new HashSet<Object>());
public BrokerConnectionListener(final String topic) {
super();
this.topic = topic;
}
void dispose() {
final String partitionPath = ProducerZooKeeper.this.metaZookeeper.brokerTopicsPubPath + "/" + this.topic;
ProducerZooKeeper.this.zkClient.unsubscribeChildChanges(partitionPath, this);
}
/**
* broker
*/
@Override
public void handleChildChange(final String parentPath, final List<String> currentChilds) throws Exception {
this.syncedUpdateBrokersInfo();
}
void syncedUpdateBrokersInfo() throws NotifyRemotingException, InterruptedException {
this.lock.lock();
try {
final Map<Integer, String> newBrokerStringMap =
ProducerZooKeeper.this.metaZookeeper.getMasterBrokersByTopic(this.topic);
final List<String> topics = new ArrayList<String>(1);
topics.add(this.topic);
final Map<String, List<Partition>> newTopicPartitionMap =
ProducerZooKeeper.this.metaZookeeper.getPartitionsForTopicsFromMaster(topics);
log.warn("Begin receiving broker changes for topic " + this.topic + ",broker ids:"
+ newTopicPartitionMap);
// Connect to new brokers
for (final Map.Entry<Integer, String> newEntry : newBrokerStringMap.entrySet()) {
final Integer newBrokerId = newEntry.getKey();
final String newBrokerString = newEntry.getValue();
// µУɵûУ
if (!this.brokersInfo.oldBrokerStringMap.containsKey(newBrokerId)) {
ProducerZooKeeper.this.remotingClient.connect(newBrokerString);
ProducerZooKeeper.this.remotingClient.awaitReadyInterrupt(newBrokerString);
log.warn("Connect to " + newBrokerString);
}
}
// Close removed brokers.
for (final Map.Entry<Integer, String> oldEntry : this.brokersInfo.oldBrokerStringMap.entrySet()) {
final Integer oldBrokerId = oldEntry.getKey();
final String oldBrokerString = oldEntry.getValue();
final String newBrokerString = newBrokerStringMap.get(oldBrokerId);
// ¾ɶ
if (newBrokerStringMap.containsKey(oldBrokerId)) {
// жǷ仯
if (!newBrokerString.equals(oldBrokerString)) {
log.warn("Close " + oldBrokerString + ",connect to " + newBrokerString);
ProducerZooKeeper.this.remotingClient.connect(newBrokerString);
ProducerZooKeeper.this.remotingClient.awaitReadyInterrupt(newBrokerString);
ProducerZooKeeper.this.remotingClient.close(oldBrokerString, false);
}
else {
// ignore
}
}
else {
// µûУɵУر
ProducerZooKeeper.this.remotingClient.close(oldBrokerString, false);
log.warn("Close " + oldBrokerString);
}
}
// Set the new brokers info.
this.brokersInfo = new BrokersInfo(newBrokerStringMap, newTopicPartitionMap);
log.warn("End receiving broker changes for topic " + this.topic);
}
finally {
this.lock.unlock();
}
}
}
public ProducerZooKeeper(final MetaZookeeper metaZookeeper, final RemotingClientWrapper remotingClient,
final ZkClient zkClient, final MetaClientConfig metaClientConfig) {
super();
this.metaZookeeper = metaZookeeper;
this.remotingClient = remotingClient;
this.zkClient = zkClient;
this.metaClientConfig = metaClientConfig;
}
public void publishTopic(final String topic, final Object ref) {
if (this.topicConnectionListeners.get(topic) != null) {
this.addRef(topic, ref);
return;
}
final FutureTask<BrokerConnectionListener> task =
new FutureTask<BrokerConnectionListener>(new Callable<BrokerConnectionListener>() {
@Override
public BrokerConnectionListener call() throws Exception {
final BrokerConnectionListener listener = new BrokerConnectionListener(topic);
if (ProducerZooKeeper.this.zkClient != null) {
ProducerZooKeeper.this.publishTopicInternal(topic, listener);
}
listener.references.add(ref);
return listener;
}
});
final FutureTask<BrokerConnectionListener> existsTask = this.topicConnectionListeners.putIfAbsent(topic, task);
if (existsTask == null) {
task.run();
}
else {
this.addRef(topic, ref);
}
}
private void addRef(final String topic, final Object ref) {
BrokerConnectionListener listener = this.getBrokerConnectionListener(topic);
if (!listener.references.contains(ref)) {
listener.references.add(ref);
}
}
public void unPublishTopic(String topic, Object ref) {
BrokerConnectionListener listener = this.getBrokerConnectionListener(topic);
if (listener != null) {
synchronized (listener.references) {
if (this.getBrokerConnectionListener(topic) == null) {
return;
}
listener.references.remove(ref);
if (listener.references.isEmpty()) {
this.topicConnectionListeners.remove(topic);
listener.dispose();
}
}
}
}
private void publishTopicInternal(final String topic, final BrokerConnectionListener listener) throws Exception,
NotifyRemotingException, InterruptedException {
final String partitionPath = this.metaZookeeper.brokerTopicsPubPath + "/" + topic;
ZkUtils.makeSurePersistentPathExists(ProducerZooKeeper.this.zkClient, partitionPath);
ProducerZooKeeper.this.zkClient.subscribeChildChanges(partitionPath, listener);
// һҪͬȴ
listener.syncedUpdateBrokersInfo();
}
BrokerConnectionListener getBrokerConnectionListener(final String topic) {
final FutureTask<BrokerConnectionListener> task = this.topicConnectionListeners.get(topic);
if (task != null) {
try {
return task.get();
}
catch (final Exception e) {
log.error("ȡBrokerConnectionListenerʧ", e);
return null;
}
}
else {
return null;
}
}
/**
* topicҷurlб
*
* @param topic
* @return
*/
Set<String> getServerUrlSetByTopic(final String topic) {
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(topic);
if (brokerConnectionListener != null) {
final BrokersInfo info = brokerConnectionListener.brokersInfo;
final Map<Integer/* broker id */, String/* server url */> brokerStringMap = info.oldBrokerStringMap;
final Map<String/* topic */, List<Partition>/* partition list */> topicPartitionMap =
info.oldTopicPartitionMap;
final List<Partition> plist = topicPartitionMap.get(topic);
if (plist != null) {
final Set<String> result = new HashSet<String>();
for (final Partition partition : plist) {
final int brokerId = partition.getBrokerId();
final String url = brokerStringMap.get(brokerId);
if (url != null) {
result.add(url);
}
}
return result;
}
}
return Collections.emptySet();
}
/**
* Ĭtopic
*
* @param topic
*/
public synchronized void setDefaultTopic(final String topic, Object ref) {
if (this.defaultTopic != null && !this.defaultTopic.equals(topic)) {
throw new IllegalStateException("Default topic has been setup already:" + this.defaultTopic);
}
this.defaultTopic = topic;
this.publishTopic(topic, ref);
}
/**
*
* ѡָbrokerڵijڷϢ˷local transaction
*
* @param topic
* @return
*/
Partition selectPartition(final String topic, final Message msg, final PartitionSelector selector,
final String serverUrl) throws MetaClientException {
boolean oldReadOnly = msg.isReadOnly();
try {
msg.setReadOnly(true);
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(topic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
final List<Partition> partitions = brokersInfo.oldTopicPartitionMap.get(topic);
final Map<Integer/* broker id */, String/* server url */> brokerStringMap =
brokersInfo.oldBrokerStringMap;
// ضbrokerķб
final List<Partition> partitionsForSelect = new ArrayList<Partition>();
for (final Partition partition : partitions) {
if (serverUrl.equals(brokerStringMap.get(partition.getBrokerId()))) {
partitionsForSelect.add(partition);
}
}
return selector.getPartition(topic, partitionsForSelect, msg);
}
else {
return this.selectDefaultPartition(topic, msg, selector, serverUrl);
}
}
finally {
msg.setReadOnly(oldReadOnly);
}
}
/**
* partitionѰbroker url
*
* @param topic
* @param message
* @return ѡеbrokerurl
*/
public String selectBroker(final String topic, final Partition partition) {
if (this.metaClientConfig.getServerUrl() != null) {
return this.metaClientConfig.getServerUrl();
}
if (partition != null) {
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(topic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
return brokersInfo.oldBrokerStringMap.get(partition.getBrokerId());
}
else {
return this.selectDefaultBroker(topic, partition);
}
}
return null;
}
/**
* defaultTopicѡbroker
*
* @param topic
* @param partition
* @return
*/
private String selectDefaultBroker(final String topic, final Partition partition) {
if (this.defaultTopic == null) {
return null;
}
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(this.defaultTopic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
return brokersInfo.oldBrokerStringMap.get(partition.getBrokerId());
}
else {
return null;
}
}
/**
* topicmessageѡ
*
* @param topic
* @param message
* @return ѡеķ
*/
public Partition selectPartition(final String topic, final Message message,
final PartitionSelector partitionSelector) throws MetaClientException {
boolean oldReadOnly = message.isReadOnly();
try {
message.setReadOnly(true);
if (this.metaClientConfig.getServerUrl() != null) {
return Partition.RandomPartiton;
}
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(topic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
return partitionSelector.getPartition(topic, brokersInfo.oldTopicPartitionMap.get(topic), message);
}
else {
return this.selectDefaultPartition(topic, message, partitionSelector, null);
}
}
finally {
message.setReadOnly(oldReadOnly);
}
}
private Partition selectDefaultPartition(final String topic, final Message message,
final PartitionSelector partitionSelector, final String serverUrl) throws MetaClientException {
if (this.defaultTopic == null) {
return null;
}
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(this.defaultTopic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
if (serverUrl == null) {
return partitionSelector.getPartition(this.defaultTopic,
brokersInfo.oldTopicPartitionMap.get(this.defaultTopic), message);
}
else {
final List<Partition> partitions = brokersInfo.oldTopicPartitionMap.get(this.defaultTopic);
final Map<Integer/* broker id */, String/* server url */> brokerStringMap =
brokersInfo.oldBrokerStringMap;
// ضbrokerķб
final List<Partition> partitionsForSelect = new ArrayList<Partition>();
for (final Partition partition : partitions) {
if (serverUrl.equals(brokerStringMap.get(partition.getBrokerId()))) {
partitionsForSelect.add(partition);
}
}
return partitionSelector.getPartition(this.defaultTopic, partitionsForSelect, message);
}
}
else {
return null;
}
}
@Override
public void onZkClientChanged(final ZkClient newClient) {
this.zkClient = newClient;
try {
for (final String topic : this.topicConnectionListeners.keySet()) {
log.info("re-publish topic to zk,topic=" + topic);
this.publishTopicInternal(topic, this.getBrokerConnectionListener(topic));
}
}
catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
catch (final Exception e) {
log.error("zKClientʧ", e);
}
}
} | metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/producer/ProducerZooKeeper.java | /*
* (C) 2007-2012 Alibaba Group Holding Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Authors:
* wuhua <[email protected]> , boyan <[email protected]>
*/
package com.taobao.metamorphosis.client.producer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.taobao.gecko.service.exception.NotifyRemotingException;
import com.taobao.metamorphosis.Message;
import com.taobao.metamorphosis.client.MetaClientConfig;
import com.taobao.metamorphosis.client.RemotingClientWrapper;
import com.taobao.metamorphosis.client.ZkClientChangedListener;
import com.taobao.metamorphosis.cluster.Partition;
import com.taobao.metamorphosis.exception.MetaClientException;
import com.taobao.metamorphosis.utils.MetaZookeeper;
import com.taobao.metamorphosis.utils.ZkUtils;
/**
* ProducerzkĽ
*
* @author boyan
* @Date 2011-4-26
*/
public class ProducerZooKeeper implements ZkClientChangedListener {
private final RemotingClientWrapper remotingClient;
private final ConcurrentHashMap<String, FutureTask<BrokerConnectionListener>> topicConnectionListeners =
new ConcurrentHashMap<String, FutureTask<BrokerConnectionListener>>();
private final MetaClientConfig metaClientConfig;
private ZkClient zkClient;
private final MetaZookeeper metaZookeeper;
/**
* Ĭtopicҷûҵ÷ʱ��͵topicµbroker
*/
private String defaultTopic;
static final Log log = LogFactory.getLog(ProducerZooKeeper.class);
public static class BrokersInfo {
final Map<Integer/* broker id */, String/* server url */> oldBrokerStringMap;
final Map<String/* topic */, List<Partition>/* partition list */> oldTopicPartitionMap;
public BrokersInfo(final Map<Integer, String> oldBrokerStringMap,
final Map<String, List<Partition>> oldTopicPartitionMap) {
super();
this.oldBrokerStringMap = oldBrokerStringMap;
this.oldTopicPartitionMap = oldTopicPartitionMap;
}
}
final class BrokerConnectionListener implements IZkChildListener {
final Lock lock = new ReentrantLock();
volatile BrokersInfo brokersInfo = new BrokersInfo(new TreeMap<Integer, String>(),
new HashMap<String, List<Partition>>());
final String topic;
final Set<Object> references = Collections.synchronizedSet(new HashSet<Object>());
public BrokerConnectionListener(final String topic) {
super();
this.topic = topic;
}
void dispose() {
final String partitionPath = ProducerZooKeeper.this.metaZookeeper.brokerTopicsPubPath + "/" + this.topic;
ProducerZooKeeper.this.zkClient.unsubscribeChildChanges(partitionPath, this);
}
/**
* broker
*/
@Override
public void handleChildChange(final String parentPath, final List<String> currentChilds) throws Exception {
this.syncedUpdateBrokersInfo();
}
void syncedUpdateBrokersInfo() throws NotifyRemotingException, InterruptedException {
this.lock.lock();
try {
final Map<Integer, String> newBrokerStringMap =
ProducerZooKeeper.this.metaZookeeper.getMasterBrokersByTopic(this.topic);
final List<String> topics = new ArrayList<String>(1);
topics.add(this.topic);
final Map<String, List<Partition>> newTopicPartitionMap =
ProducerZooKeeper.this.metaZookeeper.getPartitionsForTopicsFromMaster(topics);
log.warn("Begin receiving broker changes for topic " + this.topic + ",broker ids:"
+ newTopicPartitionMap);
// Connect to new brokers
for (final Map.Entry<Integer, String> newEntry : newBrokerStringMap.entrySet()) {
final Integer newBrokerId = newEntry.getKey();
final String newBrokerString = newEntry.getValue();
// µУɵûУ
if (!this.brokersInfo.oldBrokerStringMap.containsKey(newBrokerId)) {
ProducerZooKeeper.this.remotingClient.connect(newBrokerString);
ProducerZooKeeper.this.remotingClient.awaitReadyInterrupt(newBrokerString);
log.warn("Connect to " + newBrokerString);
}
}
// Close removed brokers.
for (final Map.Entry<Integer, String> oldEntry : this.brokersInfo.oldBrokerStringMap.entrySet()) {
final Integer oldBrokerId = oldEntry.getKey();
final String oldBrokerString = oldEntry.getValue();
final String newBrokerString = newBrokerStringMap.get(oldBrokerId);
// ¾ɶ
if (newBrokerStringMap.containsKey(oldBrokerId)) {
// жǷ仯
if (!newBrokerString.equals(oldBrokerString)) {
log.warn("Close " + oldBrokerString + ",connect to " + newBrokerString);
ProducerZooKeeper.this.remotingClient.connect(newBrokerString);
ProducerZooKeeper.this.remotingClient.awaitReadyInterrupt(newBrokerString);
ProducerZooKeeper.this.remotingClient.close(oldBrokerString, false);
}
else {
// ignore
}
}
else {
// µûУɵУر
ProducerZooKeeper.this.remotingClient.close(oldBrokerString, false);
log.warn("Close " + oldBrokerString);
}
}
// Set the new brokers info.
this.brokersInfo = new BrokersInfo(newBrokerStringMap, newTopicPartitionMap);
log.warn("End receiving broker changes for topic " + this.topic);
}
finally {
this.lock.unlock();
}
}
}
public ProducerZooKeeper(final MetaZookeeper metaZookeeper, final RemotingClientWrapper remotingClient,
final ZkClient zkClient, final MetaClientConfig metaClientConfig) {
super();
this.metaZookeeper = metaZookeeper;
this.remotingClient = remotingClient;
this.zkClient = zkClient;
this.metaClientConfig = metaClientConfig;
}
public void publishTopic(final String topic, final Object ref) {
if (this.topicConnectionListeners.get(topic) != null) {
this.addRef(topic, ref);
return;
}
final FutureTask<BrokerConnectionListener> task =
new FutureTask<BrokerConnectionListener>(new Callable<BrokerConnectionListener>() {
@Override
public BrokerConnectionListener call() throws Exception {
final BrokerConnectionListener listener = new BrokerConnectionListener(topic);
if (ProducerZooKeeper.this.zkClient != null) {
ProducerZooKeeper.this.publishTopicInternal(topic, listener);
}
listener.references.add(ref);
return listener;
}
});
final FutureTask<BrokerConnectionListener> existsTask = this.topicConnectionListeners.putIfAbsent(topic, task);
if (existsTask == null) {
task.run();
}
else {
this.addRef(topic, ref);
}
}
private void addRef(final String topic, final Object ref) {
BrokerConnectionListener listener = this.getBrokerConnectionListener(topic);
if (!listener.references.contains(ref)) {
listener.references.add(ref);
}
}
public void unPublishTopic(String topic, Object ref) {
BrokerConnectionListener listener = this.getBrokerConnectionListener(topic);
if (listener != null) {
synchronized (listener.references) {
if (this.getBrokerConnectionListener(topic) == null) {
return;
}
listener.references.remove(ref);
if (listener.references.isEmpty()) {
this.topicConnectionListeners.remove(topic);
listener.dispose();
}
}
}
}
private void publishTopicInternal(final String topic, final BrokerConnectionListener listener) throws Exception,
NotifyRemotingException, InterruptedException {
final String partitionPath = this.metaZookeeper.brokerTopicsPubPath + "/" + topic;
ZkUtils.makeSurePersistentPathExists(ProducerZooKeeper.this.zkClient, partitionPath);
ProducerZooKeeper.this.zkClient.subscribeChildChanges(partitionPath, listener);
// һҪͬȴ
listener.syncedUpdateBrokersInfo();
}
BrokerConnectionListener getBrokerConnectionListener(final String topic) {
final FutureTask<BrokerConnectionListener> task = this.topicConnectionListeners.get(topic);
if (task != null) {
try {
return task.get();
}
catch (final Exception e) {
log.error("ȡBrokerConnectionListenerʧ", e);
return null;
}
}
else {
return null;
}
}
/**
* topicҷurlб
*
* @param topic
* @return
*/
Set<String> getServerUrlSetByTopic(final String topic) {
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(topic);
if (brokerConnectionListener != null) {
final BrokersInfo info = brokerConnectionListener.brokersInfo;
final Map<Integer/* broker id */, String/* server url */> brokerStringMap = info.oldBrokerStringMap;
final Map<String/* topic */, List<Partition>/* partition list */> topicPartitionMap =
info.oldTopicPartitionMap;
final List<Partition> plist = topicPartitionMap.get(topic);
if (plist != null) {
final Set<String> result = new HashSet<String>();
for (final Partition partition : plist) {
final int brokerId = partition.getBrokerId();
final String url = brokerStringMap.get(brokerId);
if (url != null) {
result.add(url);
}
}
return result;
}
}
return Collections.emptySet();
}
/**
* Ĭtopic
*
* @param topic
*/
public synchronized void setDefaultTopic(final String topic, Object ref) {
if (this.defaultTopic != null && !this.defaultTopic.equals(topic)) {
throw new IllegalStateException("Default topic has been setup already:" + this.defaultTopic);
}
this.defaultTopic = topic;
this.publishTopic(topic, ref);
}
/**
*
* ѡָbrokerڵijڷϢ˷local transaction
*
* @param topic
* @return
*/
Partition selectPartition(final String topic, final Message msg, final PartitionSelector selector,
final String serverUrl) throws MetaClientException {
try {
msg.setReadOnly(true);
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(topic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
final List<Partition> partitions = brokersInfo.oldTopicPartitionMap.get(topic);
final Map<Integer/* broker id */, String/* server url */> brokerStringMap =
brokersInfo.oldBrokerStringMap;
// ضbrokerķб
final List<Partition> partitionsForSelect = new ArrayList<Partition>();
for (final Partition partition : partitions) {
if (serverUrl.equals(brokerStringMap.get(partition.getBrokerId()))) {
partitionsForSelect.add(partition);
}
}
return selector.getPartition(topic, partitionsForSelect, msg);
}
else {
return this.selectDefaultPartition(topic, msg, selector, serverUrl);
}
}
finally {
msg.setReadOnly(false);
}
}
/**
* partitionѰbroker url
*
* @param topic
* @param message
* @return ѡеbrokerurl
*/
public String selectBroker(final String topic, final Partition partition) {
if (this.metaClientConfig.getServerUrl() != null) {
return this.metaClientConfig.getServerUrl();
}
if (partition != null) {
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(topic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
return brokersInfo.oldBrokerStringMap.get(partition.getBrokerId());
}
else {
return this.selectDefaultBroker(topic, partition);
}
}
return null;
}
/**
* defaultTopicѡbroker
*
* @param topic
* @param partition
* @return
*/
private String selectDefaultBroker(final String topic, final Partition partition) {
if (this.defaultTopic == null) {
return null;
}
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(this.defaultTopic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
return brokersInfo.oldBrokerStringMap.get(partition.getBrokerId());
}
else {
return null;
}
}
/**
* topicmessageѡ
*
* @param topic
* @param message
* @return ѡеķ
*/
public Partition selectPartition(final String topic, final Message message,
final PartitionSelector partitionSelector) throws MetaClientException {
try {
message.setReadOnly(true);
if (this.metaClientConfig.getServerUrl() != null) {
return Partition.RandomPartiton;
}
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(topic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
return partitionSelector.getPartition(topic, brokersInfo.oldTopicPartitionMap.get(topic), message);
}
else {
return this.selectDefaultPartition(topic, message, partitionSelector, null);
}
}
finally {
message.setReadOnly(false);
}
}
private Partition selectDefaultPartition(final String topic, final Message message,
final PartitionSelector partitionSelector, final String serverUrl) throws MetaClientException {
if (this.defaultTopic == null) {
return null;
}
final BrokerConnectionListener brokerConnectionListener = this.getBrokerConnectionListener(this.defaultTopic);
if (brokerConnectionListener != null) {
final BrokersInfo brokersInfo = brokerConnectionListener.brokersInfo;
if (serverUrl == null) {
return partitionSelector.getPartition(this.defaultTopic,
brokersInfo.oldTopicPartitionMap.get(this.defaultTopic), message);
}
else {
final List<Partition> partitions = brokersInfo.oldTopicPartitionMap.get(this.defaultTopic);
final Map<Integer/* broker id */, String/* server url */> brokerStringMap =
brokersInfo.oldBrokerStringMap;
// ضbrokerķб
final List<Partition> partitionsForSelect = new ArrayList<Partition>();
for (final Partition partition : partitions) {
if (serverUrl.equals(brokerStringMap.get(partition.getBrokerId()))) {
partitionsForSelect.add(partition);
}
}
return partitionSelector.getPartition(this.defaultTopic, partitionsForSelect, message);
}
}
else {
return null;
}
}
@Override
public void onZkClientChanged(final ZkClient newClient) {
this.zkClient = newClient;
try {
for (final String topic : this.topicConnectionListeners.keySet()) {
log.info("re-publish topic to zk,topic=" + topic);
this.publishTopicInternal(topic, this.getBrokerConnectionListener(topic));
}
}
catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
catch (final Exception e) {
log.error("zKClientʧ", e);
}
}
} | Keep readonly to be consistent with user setting
| metamorphosis-client/src/main/java/com/taobao/metamorphosis/client/producer/ProducerZooKeeper.java | Keep readonly to be consistent with user setting |
|
Java | apache-2.0 | aed3d6ef4f5a82d85250330573bb6c777ed466ca | 0 | ToureNPlaner/tourenplaner-server,ToureNPlaner/tourenplaner-server,ToureNPlaner/tourenplaner-server,ToureNPlaner/tourenplaner-server | package de.tourenplaner.server;
import de.tourenplaner.database.*;
import de.tourenplaner.utils.SHA1;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferInputStream;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* @author Christoph Haag, Sascha Meusel, Niklas Schnelle, Peter Vollmer
*
*/
public class PrivateHandler extends RequestHandler {
private static Logger log = Logger.getLogger("de.tourenplaner.server");
private final DatabaseManager dbm;
private final Authorizer authorizer;
private static final ObjectMapper mapper = new ObjectMapper();
public PrivateHandler(Authorizer authorizer, DatabaseManager dbm) {
super(null);
this.dbm = dbm;
this.authorizer = authorizer;
}
/**
* Extracts and parses the JSON encoded content of the given HttpRequest, in
* case of error sends a EBADJSON answer to the client and returns null,
* the connection will be closed afterwards.
*
* @param request HttpRequest
* @return Returns parsed json map or null in case of an error
* @throws IOException Thrown if error message sending or reading json content fails
* @throws JsonMappingException Thrown if mapping json content fails
*/
private Map<String, Object> getJSONContent(final HttpRequest request) throws IOException {
Map<String, Object> objmap = null;
final ChannelBuffer content = request.getContent();
if (content.readableBytes() > 0) {
try {
objmap = mapper.readValue(new ChannelBufferInputStream(content), new TypeReference<Map<String, Object>>() {
});
} catch (JsonParseException e) {
responder.writeErrorMessage(ErrorMessage.EBADJSON, e.getMessage());
objmap = null;
}
} else {
responder.writeErrorMessage(ErrorMessage.EBADJSON_NOCONTENT);
}
return objmap;
}
/**
* If authorization is okay, but no admin, registration fails. If no
* authorization as admin, the new registered user will not be registered as
* admin, even if json admin flag is true.
*
* @param request HttpRequest
* @throws SQLFeatureNotSupportedException
* Thrown if a function is not supported by driver.
* @throws SQLException
* Thrown if database query fails
* @throws JsonMappingException
* Thrown if mapping object to json fails
* @throws JsonGenerationException
* Thrown if generating json fails
* @throws IOException
* Thrown if error message sending or reading/writing json content fails
*/
public void handleRegisterUser(final HttpRequest request) throws IOException, SQLException {
UserDataset authenticatedUser = null;
// if no authorization header keep on with adding not verified user
if (request.getHeader("Authorization") != null) {
authenticatedUser = authorizer.auth(request);
if (authenticatedUser == null) {
// auth(request) sent error response
return;
}
if (!authenticatedUser.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_REGISTER_USER);
return;
}
}
Map<String, Object> objmap = getJSONContent(request);
// getJSONContent adds error-message to responder
// if json object is bad or if there is no json object
// so no further handling needed if objmap == null
if (objmap == null) {
log.warning("Failed, bad json object.");
return;
}
if ( !(objmap.get("email") instanceof String) || !(objmap.get("password") instanceof String)
|| !(objmap.get("firstname") instanceof String) || !(objmap.get("lastname") instanceof String)
|| !(objmap.get("address") instanceof String) ) {
responder.writeErrorMessage(ErrorMessage.EBADJSON_INCORRECT_USER_OBJ);
return;
}
final String email = (String) objmap.get("email");
final String pw = (String) objmap.get("password");
final String firstName = (String) objmap.get("firstname");
final String lastName = (String) objmap.get("lastname");
final String address = (String) objmap.get("address");
if ((pw == null) || (email == null) || (firstName == null) || (lastName == null) || (address == null)) {
responder.writeErrorMessage(ErrorMessage.EBADJSON_INCORRECT_USER_OBJ);
return;
}
final String salt = authorizer.generateSalt();
final String toHash = SHA1.SHA1(pw + ':' + salt);
UserDataset newUser;
// if there is no authorization, add user but without verification
if (authenticatedUser == null) {
// if there is no authorization as admin, the new registered user will
// never be registered as admin, even if json admin flag is true
newUser = dbm.addNewUser(email, toHash, salt, firstName, lastName, address, false);
} else {
boolean adminFlag = false;
if (objmap.get("admin") != null) {
// if (objmap.get("admin") is null, then "instanceof Boolean" would be always false
// so following check makes only sense if objmap.get("admin") != null
if ( !(objmap.get("admin") instanceof Boolean) ) {
responder.writeErrorMessage(ErrorMessage.EBADJSON_INCORRECT_USER_OBJ_ADMIN);
return;
}
adminFlag = (Boolean) objmap.get("admin");
}
newUser = dbm.addNewVerifiedUser(email, toHash, salt, firstName, lastName, address, adminFlag);
}
if ( newUser == null) {
responder.writeErrorMessage(ErrorMessage.EREGISTERED);
return;
}
responder.writeJSON(newUser, HttpResponseStatus.OK);
log.finest("RegisterUser successful.");
}
/**
* Authenticates the client and sends the corresponding user object as json to the client.
*
* @param request HttpRequest
* @throws SQLException Thrown if database query fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleAuthUser(final HttpRequest request) throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
if (user != null) {
responder.writeJSON(user, HttpResponseStatus.OK);
}
}
/**
* Sends the data of one user as json to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleGetUser(final HttpRequest request, Map<String, List<String>> parameters)
throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int userID;
UserDataset selectedUser;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, false);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID < 0) {
return;
}
selectedUser = dbm.getUser(userID);
} else {
selectedUser = user;
}
if (selectedUser == null) {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_IN_DB);
return;
}
responder.writeJSON(selectedUser, HttpResponseStatus.OK);
log.finest("GetUser successful.");
}
/**
* Updates the data of a user.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws IOException Thrown if error message sending or reading/writing json content fails
*/
public void handleUpdateUser(final HttpRequest request, Map<String, List<String>> parameters)
throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
Map<String, Object> objmap = getJSONContent(request);
// getJSONContent adds error-message to responder
// if json object is bad or if there is no json object
// so no further handling needed if objmap == null
if (objmap == null) {
log.warning("Failed, bad json object.");
return;
}
int userID;
boolean isAdmin = user.admin;
UserDataset selectedUser;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, false);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID < 0) {
return;
}
selectedUser = dbm.getUser(userID);
if (selectedUser == null) {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_IN_DB);
return;
}
} else {
selectedUser = user;
}
if (objmap.get("password") != null && (objmap.get("password") instanceof String)) {
selectedUser.salt = authorizer.generateSalt();
selectedUser.passwordhash = SHA1.SHA1((String) objmap.get("password") + ':' + selectedUser.salt);
}
if (isAdmin) {
if (objmap.get("email") != null && (objmap.get("email") instanceof String)) {
selectedUser.email = (String) objmap.get("email");
}
if (objmap.get("firstname") != null && (objmap.get("firstname") instanceof String)) {
selectedUser.firstName = (String) objmap.get("firstname");
}
if (objmap.get("lastname") != null && (objmap.get("lastname") instanceof String)) {
selectedUser.lastName = (String) objmap.get("lastname");
}
if (objmap.get("address") != null && (objmap.get("address") instanceof String)) {
selectedUser.address = (String) objmap.get("address");
}
// the user with id = 1 should always be admin, so no admin flag changing
if (selectedUser.userid != 1 && objmap.get("admin") != null && (objmap.get("admin") instanceof Boolean)) {
selectedUser.admin = (Boolean) objmap.get("admin");
}
// the user with id = 1 should always be verified, so no status changing
if (selectedUser.userid != 1 && objmap.get("status") != null && (objmap.get("status") instanceof String)) {
String status = (String) objmap.get("status");
UserStatusEnum previousStatus = selectedUser.status;
try {
selectedUser.status = UserStatusEnum.valueOf(status);
} catch (IllegalArgumentException e) {
responder.writeErrorMessage(ErrorMessage.EBADJSON_INCORRECT_USER_OBJ_STATUS);
return;
}
if (previousStatus == UserStatusEnum.needs_verification
&& selectedUser.status == UserStatusEnum.verified) {
selectedUser.verifiedDate = new Date(System.currentTimeMillis());
}
}
}
userID = selectedUser.userid;
int rowsChanged = dbm.updateUser(selectedUser);
if (rowsChanged == -1) {
responder.writeErrorMessage(ErrorMessage.EREGISTERED);
return;
}
responder.writeJSON(dbm.getUser(userID), HttpResponseStatus.OK);
log.finest("UpdateUser successful.");
}
/**
* Sends the JsonRequest of the request with the given id to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws IOException Thrown if error message sending or writing content fails
*/
public void handleGetRequest(final HttpRequest request, Map<String, List<String>> parameters) throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int requestID;
JSONObject jsonObject;
if (parameters.containsKey("id")) {
requestID = parseRequestIdParameter(parameters.get("id").get(0));
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (requestID < 0) {
return;
}
jsonObject = dbm.getJsonRequest(requestID);
if (jsonObject == null) {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_NOT_IN_DB);
return;
}
} else {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_MISSING);
return;
}
if (user.userid != jsonObject.getUserID() && !user.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_OTHER_USER_REQUEST);
return;
}
responder.writeByteArray(jsonObject.getJsonByteArray(), HttpResponseStatus.OK);
log.finest("GetRequest successful.");
}
/**
* Sends the JsonResponse of the request with the given id to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws IOException Thrown if error message sending or writing content fails
*/
public void handleGetResponse(final HttpRequest request, Map<String, List<String>> parameters) throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int requestID;
JSONObject jsonObject;
if (parameters.containsKey("id")) {
requestID = parseRequestIdParameter(parameters.get("id").get(0));
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (requestID < 0) {
return;
}
jsonObject = dbm.getJsonResponse(requestID);
if (jsonObject == null) {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_NOT_IN_DB);
return;
}
} else {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_MISSING);
return;
}
if (user.userid != jsonObject.getUserID() && !user.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_OTHER_USER_REQUEST);
return;
}
responder.writeByteArray(jsonObject.getJsonByteArray(), HttpResponseStatus.OK);
log.finest("GetResponse successful.");
}
/**
* Sends a list with requests as json to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleListRequests(final HttpRequest request, Map<String, List<String>> parameters)
throws SQLException, IOException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth
// fails
if (user == null) {
return;
}
int limit = extractNaturalIntParameter(parameters, "limit", ErrorMessage.ELIMIT_MISSING,
ErrorMessage.ELIMIT_NOT_NAT_NUMBER);
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (limit < 0) {
return;
}
int offset = extractNaturalIntParameter(parameters, "offset", ErrorMessage.EOFFSET_MISSING,
ErrorMessage.EOFFSET_NOT_NAT_NUMBER);
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (offset < 0) {
return;
}
Integer userID;
boolean allRequests = false;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, true);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID != null && userID < 0) {
return;
}
if (userID == null) {
allRequests = true;
}
} else {
userID = user.userid;
}
List<RequestDataset> requestDatasetList;
int count;
if (allRequests) {
requestDatasetList = dbm.getAllRequests(limit, offset);
count = dbm.getNumberOfRequests();
} else {
requestDatasetList = dbm.getRequests(userID, limit, offset);
count = dbm.getNumberOfRequestsWithUserId(userID);
}
Map<String, Object> responseMap = new HashMap<String, Object>(2);
responseMap.put("number", count);
responseMap.put("requests", requestDatasetList);
responder.writeJSON(responseMap, HttpResponseStatus.OK);
log.finest("ListRequests successful.");
}
/**
* Sends a list with users as json to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleListUsers(final HttpRequest request, Map<String, List<String>> parameters)
throws SQLException, IOException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
if (!user.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_LIST_USERS);
return;
}
int limit = extractNaturalIntParameter(parameters, "limit", ErrorMessage.ELIMIT_MISSING,
ErrorMessage.ELIMIT_NOT_NAT_NUMBER);
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (limit < 0) {
return;
}
int offset = extractNaturalIntParameter(parameters, "offset", ErrorMessage.EOFFSET_MISSING,
ErrorMessage.EOFFSET_NOT_NAT_NUMBER);
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (offset < 0) {
return;
}
List<UserDataset> userDatasetList;
userDatasetList = dbm.getAllUsers(limit, offset);
int count = dbm.getNumberOfUsers();
Map<String, Object> responseMap = new HashMap<String, Object>(2);
responseMap.put("number", count);
responseMap.put("users", userDatasetList);
responder.writeJSON(responseMap, HttpResponseStatus.OK);
log.finest("ListUsers successful.");
}
/**
* Sets the status flag of the user to deleted.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws IOException Thrown if error message sending fails
* @throws SQLException Thrown if database query fails
*/
public void handleDeleteUser(final HttpRequest request, Map<String, List<String>> parameters)
throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int userID;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, false);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID < 0) {
return;
}
} else {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_MISSING);
return;
}
// the user with id = 1 should always be verified, so no status changing
if (userID != 1) {
if (dbm.updateUserStatusToDeleted(userID) != 1) {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_IN_DB);
return;
}
}
responder.writeStatusResponse(HttpResponseStatus.OK);
log.finest("DeleteUser successful.");
}
/**
* Returns the parsed number or -1 if parameter is invalid (not a natural number) and will then
* response to request with error message.
* @param parameterValue the value of the id parameter as String
* @return Returns the parsed number or -1 if parameter is invalid (not a natural number)
* @throws IOException Thrown if error message sending fails
*/
private int parseRequestIdParameter(String parameterValue) throws IOException {
int requestID;
try {
requestID = Integer.parseInt(parameterValue);
} catch (NumberFormatException e) {
requestID = -1;
}
if (requestID < 0) {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_NOT_NAT_NUMBER);
return requestID;
}
return requestID;
}
/**
* Returns the parsed number or -1 if parameter is invalid (not a natural number) and will then
* response to request with error message. But the authenticated user must be an admin (will be checked by this
* method) or an error message will be sent. If "id=all" is allowed and the value of the parameter is "all",
* this method will return null.
* @param parameterValue the value of the id parameter as String
* @param authenticatedUser UserDataset of the user who sent the request
* @param valueAllIsAllowed determines if id=all is allowed for the parameter
* @return Returns the parsed number or -1 if parameter is invalid (not a natural number).
* If "id=all" is allowed and the value of the parameter is "all",
* this method will return null.
* @throws IOException Thrown if error message sending fails
*/
private Integer parseUserIdParameter(String parameterValue, UserDataset authenticatedUser,
boolean valueAllIsAllowed) throws IOException {
if (!authenticatedUser.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_USER_ID_PARAM);
return -1;
}
int userID;
if ("all".equals(parameterValue) && valueAllIsAllowed) {
return null;
} else {
try {
userID = Integer.parseInt(parameterValue);
} catch (NumberFormatException e) {
userID = -1;
}
}
if (userID < 0) {
if (valueAllIsAllowed) {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_NAT_NUMBER_OR_ALL);
} else {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_NAT_NUMBER);
}
return userID;
}
return userID;
}
/**
* Returns the parsed number or -1 if parameter is invalid (missing or not a natural number)
* and will then response to request with error message.
* @param parameters map with url parameters from client
* @param name the name of the parameter
* @param eMissing the corresponding ErrorMessage to the parameter if parameter is missing
* @param eNotNaturalNumber the corresponding ErrorMessage to the parameter if parameter is not a natural number
* @return Returns the parsed number or -1 if parameter is invalid (missing or not a natural number)
* @throws IOException Thrown if error message sending fails
*/
private int extractNaturalIntParameter(Map<String, List<String>> parameters, String name,
ErrorMessage eMissing, ErrorMessage eNotNaturalNumber)
throws IOException {
int param;
if (!parameters.containsKey(name) || parameters.get(name).get(0) == null) {
responder.writeErrorMessage(eMissing);
return -1;
}
try {
param = Integer.parseInt(parameters.get(name).get(0));
} catch (NumberFormatException e) {
param = -1;
}
if (param < 0) {
responder.writeErrorMessage(eNotNaturalNumber);
return -1;
}
return param;
}
}
| src/de/tourenplaner/server/PrivateHandler.java | package de.tourenplaner.server;
import de.tourenplaner.database.*;
import de.tourenplaner.utils.SHA1;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferInputStream;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* @author Christoph Haag, Sascha Meusel, Niklas Schnelle, Peter Vollmer
*
*/
public class PrivateHandler extends RequestHandler {
private static Logger log = Logger.getLogger("de.tourenplaner.server");
private final DatabaseManager dbm;
private final Authorizer authorizer;
private static final ObjectMapper mapper = new ObjectMapper();
public PrivateHandler(Authorizer authorizer, DatabaseManager dbm) {
super(null);
this.dbm = dbm;
this.authorizer = authorizer;
}
/**
* Extracts and parses the JSON encoded content of the given HttpRequest, in
* case of error sends a EBADJSON answer to the client and returns null,
* the connection will be closed afterwards.
*
* @param request HttpRequest
* @return Returns parsed json map or null in case of an error
* @throws IOException Thrown if error message sending or reading json content fails
* @throws JsonMappingException Thrown if mapping json content fails
*/
private Map<String, Object> getJSONContent(final HttpRequest request) throws IOException {
Map<String, Object> objmap = null;
final ChannelBuffer content = request.getContent();
if (content.readableBytes() > 0) {
try {
objmap = mapper.readValue(new ChannelBufferInputStream(content), new TypeReference<Map<String, Object>>() {
});
} catch (JsonParseException e) {
responder.writeErrorMessage(ErrorMessage.EBADJSON, e.getMessage());
objmap = null;
}
} else {
responder.writeErrorMessage(ErrorMessage.EBADJSON_NOCONTENT);
}
return objmap;
}
/**
* If authorization is okay, but no admin, registration fails. If no
* authorization as admin, the new registered user will not be registered as
* admin, even if json admin flag is true.
*
* @param request HttpRequest
* @throws SQLFeatureNotSupportedException
* Thrown if a function is not supported by driver.
* @throws SQLException
* Thrown if database query fails
* @throws JsonMappingException
* Thrown if mapping object to json fails
* @throws JsonGenerationException
* Thrown if generating json fails
* @throws IOException
* Thrown if error message sending or reading/writing json content fails
*/
public void handleRegisterUser(final HttpRequest request) throws IOException, SQLException {
UserDataset authenticatedUser = null;
// if no authorization header keep on with adding not verified user
if (request.getHeader("Authorization") != null) {
authenticatedUser = authorizer.auth(request);
if (authenticatedUser == null) {
// auth(request) sent error response
return;
}
if (!authenticatedUser.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_REGISTER_USER);
return;
}
}
Map<String, Object> objmap = getJSONContent(request);
// getJSONContent adds error-message to responder
// if json object is bad or if there is no json object
// so no further handling needed if objmap == null
if (objmap == null) {
log.warning("Failed, bad json object.");
return;
}
if ( !(objmap.get("email") instanceof String) || !(objmap.get("password") instanceof String)
|| !(objmap.get("firstname") instanceof String) || !(objmap.get("lastname") instanceof String)
|| !(objmap.get("address") instanceof String) ) {
responder.writeErrorMessage(ErrorMessage.EBADJSON_INCORRECT_USER_OBJ);
return;
}
final String email = (String) objmap.get("email");
final String pw = (String) objmap.get("password");
final String firstName = (String) objmap.get("firstname");
final String lastName = (String) objmap.get("lastname");
final String address = (String) objmap.get("address");
if ((pw == null) || (email == null) || (firstName == null) || (lastName == null) || (address == null)) {
responder.writeErrorMessage(ErrorMessage.EBADJSON_INCORRECT_USER_OBJ);
return;
}
final String salt = authorizer.generateSalt();
final String toHash = SHA1.SHA1(pw + ':' + salt);
UserDataset newUser;
// if there is no authorization, add user but without verification
if (authenticatedUser == null) {
// if there is no authorization as admin, the new registered user will
// never be registered as admin, even if json admin flag is true
newUser = dbm.addNewUser(email, toHash, salt, firstName, lastName, address, false);
} else {
boolean adminFlag = false;
if (objmap.get("admin") != null) {
// if (objmap.get("admin") is null, then "instanceof Boolean" would be always false
// so following check makes only sense if objmap.get("admin") != null
if ( !(objmap.get("admin") instanceof Boolean) ) {
responder.writeErrorMessage(ErrorMessage.EBADJSON_INCORRECT_USER_OBJ_ADMIN);
return;
}
adminFlag = (Boolean) objmap.get("admin");
}
newUser = dbm.addNewVerifiedUser(email, toHash, salt, firstName, lastName, address, adminFlag);
}
if ( newUser == null) {
responder.writeErrorMessage(ErrorMessage.EREGISTERED);
return;
}
responder.writeJSON(newUser, HttpResponseStatus.OK);
log.finest("RegisterUser successful.");
}
/**
* Authenticates the client and sends the corresponding user object as json to the client.
*
* @param request HttpRequest
* @throws SQLException Thrown if database query fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleAuthUser(final HttpRequest request) throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
if (user != null) {
responder.writeJSON(user, HttpResponseStatus.OK);
}
}
/**
* Sends the data of one user as json to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleGetUser(final HttpRequest request, Map<String, List<String>> parameters)
throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int userID;
UserDataset selectedUser;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, false);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID < 0) {
return;
}
selectedUser = dbm.getUser(userID);
} else {
selectedUser = user;
}
if (selectedUser == null) {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_IN_DB);
return;
}
responder.writeJSON(selectedUser, HttpResponseStatus.OK);
log.finest("GetUser successful.");
}
/**
* Updates the data of a user.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws IOException Thrown if error message sending or reading/writing json content fails
*/
public void handleUpdateUser(final HttpRequest request, Map<String, List<String>> parameters)
throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
Map<String, Object> objmap = getJSONContent(request);
// getJSONContent adds error-message to responder
// if json object is bad or if there is no json object
// so no further handling needed if objmap == null
if (objmap == null) {
log.warning("Failed, bad json object.");
return;
}
int userID;
boolean isAdmin = user.admin;
UserDataset selectedUser;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, false);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID < 0) {
return;
}
selectedUser = dbm.getUser(userID);
if (selectedUser == null) {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_IN_DB);
return;
}
} else {
selectedUser = user;
}
if (objmap.get("password") != null && (objmap.get("password") instanceof String)) {
selectedUser.salt = authorizer.generateSalt();
selectedUser.passwordhash = SHA1.SHA1((String) objmap.get("password") + ':' + selectedUser.salt);
}
if (isAdmin) {
if (objmap.get("email") != null && (objmap.get("email") instanceof String)) {
selectedUser.email = (String) objmap.get("email");
}
if (objmap.get("firstname") != null && (objmap.get("firstname") instanceof String)) {
selectedUser.firstName = (String) objmap.get("firstname");
}
if (objmap.get("lastname") != null && (objmap.get("lastname") instanceof String)) {
selectedUser.lastName = (String) objmap.get("lastname");
}
if (objmap.get("address") != null && (objmap.get("address") instanceof String)) {
selectedUser.address = (String) objmap.get("address");
}
// the user with id = 1 should always be admin, so no admin flag changing
if (selectedUser.userid != 1 && objmap.get("admin") != null && (objmap.get("admin") instanceof Boolean)) {
selectedUser.admin = (Boolean) objmap.get("admin");
}
// the user with id = 1 should always be verified, so no status changing
if (selectedUser.userid != 1 && objmap.get("status") != null && (objmap.get("status") instanceof String)) {
String status = (String) objmap.get("status");
UserStatusEnum previousStatus = selectedUser.status;
try {
selectedUser.status = UserStatusEnum.valueOf(status);
} catch (IllegalArgumentException e) {
responder.writeErrorMessage(ErrorMessage.EBADJSON_INCORRECT_USER_OBJ_STATUS);
return;
}
if (previousStatus == UserStatusEnum.needs_verification
&& selectedUser.status == UserStatusEnum.verified) {
selectedUser.verifiedDate = new Date(System.currentTimeMillis());
}
}
}
int rowsChanged = dbm.updateUser(selectedUser);
if (rowsChanged == -1) {
responder.writeErrorMessage(ErrorMessage.EREGISTERED);
return;
}
responder.writeJSON(selectedUser, HttpResponseStatus.OK);
log.finest("UpdateUser successful.");
}
/**
* Sends the JsonRequest of the request with the given id to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws IOException Thrown if error message sending or writing content fails
*/
public void handleGetRequest(final HttpRequest request, Map<String, List<String>> parameters) throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int requestID;
JSONObject jsonObject;
if (parameters.containsKey("id")) {
requestID = parseRequestIdParameter(parameters.get("id").get(0));
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (requestID < 0) {
return;
}
jsonObject = dbm.getJsonRequest(requestID);
if (jsonObject == null) {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_NOT_IN_DB);
return;
}
} else {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_MISSING);
return;
}
if (user.userid != jsonObject.getUserID() && !user.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_OTHER_USER_REQUEST);
return;
}
responder.writeByteArray(jsonObject.getJsonByteArray(), HttpResponseStatus.OK);
log.finest("GetRequest successful.");
}
/**
* Sends the JsonResponse of the request with the given id to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws IOException Thrown if error message sending or writing content fails
*/
public void handleGetResponse(final HttpRequest request, Map<String, List<String>> parameters) throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int requestID;
JSONObject jsonObject;
if (parameters.containsKey("id")) {
requestID = parseRequestIdParameter(parameters.get("id").get(0));
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (requestID < 0) {
return;
}
jsonObject = dbm.getJsonResponse(requestID);
if (jsonObject == null) {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_NOT_IN_DB);
return;
}
} else {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_MISSING);
return;
}
if (user.userid != jsonObject.getUserID() && !user.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_OTHER_USER_REQUEST);
return;
}
responder.writeByteArray(jsonObject.getJsonByteArray(), HttpResponseStatus.OK);
log.finest("GetResponse successful.");
}
/**
* Sends a list with requests as json to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleListRequests(final HttpRequest request, Map<String, List<String>> parameters)
throws SQLException, IOException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth
// fails
if (user == null) {
return;
}
int limit = extractNaturalIntParameter(parameters, "limit", ErrorMessage.ELIMIT_MISSING,
ErrorMessage.ELIMIT_NOT_NAT_NUMBER);
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (limit < 0) {
return;
}
int offset = extractNaturalIntParameter(parameters, "offset", ErrorMessage.EOFFSET_MISSING,
ErrorMessage.EOFFSET_NOT_NAT_NUMBER);
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (offset < 0) {
return;
}
Integer userID;
boolean allRequests = false;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, true);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID != null && userID < 0) {
return;
}
if (userID == null) {
allRequests = true;
}
} else {
userID = user.userid;
}
List<RequestDataset> requestDatasetList;
int count;
if (allRequests) {
requestDatasetList = dbm.getAllRequests(limit, offset);
count = dbm.getNumberOfRequests();
} else {
requestDatasetList = dbm.getRequests(userID, limit, offset);
count = dbm.getNumberOfRequestsWithUserId(userID);
}
Map<String, Object> responseMap = new HashMap<String, Object>(2);
responseMap.put("number", count);
responseMap.put("requests", requestDatasetList);
responder.writeJSON(responseMap, HttpResponseStatus.OK);
log.finest("ListRequests successful.");
}
/**
* Sends a list with users as json to the client.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws SQLException Thrown if database query fails
* @throws JsonGenerationException Thrown if generating json fails
* @throws JsonMappingException Thrown if mapping object to json fails
* @throws IOException Thrown if error message sending or writing json content fails
*/
public void handleListUsers(final HttpRequest request, Map<String, List<String>> parameters)
throws SQLException, IOException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
if (!user.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_LIST_USERS);
return;
}
int limit = extractNaturalIntParameter(parameters, "limit", ErrorMessage.ELIMIT_MISSING,
ErrorMessage.ELIMIT_NOT_NAT_NUMBER);
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (limit < 0) {
return;
}
int offset = extractNaturalIntParameter(parameters, "offset", ErrorMessage.EOFFSET_MISSING,
ErrorMessage.EOFFSET_NOT_NAT_NUMBER);
// if parameter is invalid, an error response is sent from extractNaturalIntParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (offset < 0) {
return;
}
List<UserDataset> userDatasetList;
userDatasetList = dbm.getAllUsers(limit, offset);
int count = dbm.getNumberOfUsers();
Map<String, Object> responseMap = new HashMap<String, Object>(2);
responseMap.put("number", count);
responseMap.put("users", userDatasetList);
responder.writeJSON(responseMap, HttpResponseStatus.OK);
log.finest("ListUsers successful.");
}
/**
* Sets the status flag of the user to deleted.
*
* @param request HttpRequest
* @param parameters map with url parameters from client
* @throws IOException Thrown if error message sending fails
* @throws SQLException Thrown if database query fails
*/
public void handleDeleteUser(final HttpRequest request, Map<String, List<String>> parameters)
throws IOException, SQLException {
UserDataset user = authorizer.auth(request);
// authentication needed, auth(request) responses with error if auth fails
if (user == null) {
return;
}
int userID;
if (parameters.containsKey("id")) {
userID = parseUserIdParameter(parameters.get("id").get(0), user, false);
// if parameter is invalid, an error response is sent from parseUserIdParameter.
// the if and return is needed exactly here, because following methods could send more responses,
// but only one response per http request is allowed (else Exceptions will be thrown)
if (userID < 0) {
return;
}
} else {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_MISSING);
return;
}
// the user with id = 1 should always be verified, so no status changing
if (userID != 1) {
if (dbm.updateUserStatusToDeleted(userID) != 1) {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_IN_DB);
return;
}
}
responder.writeStatusResponse(HttpResponseStatus.OK);
log.finest("DeleteUser successful.");
}
/**
* Returns the parsed number or -1 if parameter is invalid (not a natural number) and will then
* response to request with error message.
* @param parameterValue the value of the id parameter as String
* @return Returns the parsed number or -1 if parameter is invalid (not a natural number)
* @throws IOException Thrown if error message sending fails
*/
private int parseRequestIdParameter(String parameterValue) throws IOException {
int requestID;
try {
requestID = Integer.parseInt(parameterValue);
} catch (NumberFormatException e) {
requestID = -1;
}
if (requestID < 0) {
responder.writeErrorMessage(ErrorMessage.ENOREQUESTID_NOT_NAT_NUMBER);
return requestID;
}
return requestID;
}
/**
* Returns the parsed number or -1 if parameter is invalid (not a natural number) and will then
* response to request with error message. But the authenticated user must be an admin (will be checked by this
* method) or an error message will be sent. If "id=all" is allowed and the value of the parameter is "all",
* this method will return null.
* @param parameterValue the value of the id parameter as String
* @param authenticatedUser UserDataset of the user who sent the request
* @param valueAllIsAllowed determines if id=all is allowed for the parameter
* @return Returns the parsed number or -1 if parameter is invalid (not a natural number).
* If "id=all" is allowed and the value of the parameter is "all",
* this method will return null.
* @throws IOException Thrown if error message sending fails
*/
private Integer parseUserIdParameter(String parameterValue, UserDataset authenticatedUser,
boolean valueAllIsAllowed) throws IOException {
if (!authenticatedUser.admin) {
responder.writeErrorMessage(ErrorMessage.ENOTADMIN_USER_ID_PARAM);
return -1;
}
int userID;
if ("all".equals(parameterValue) && valueAllIsAllowed) {
return null;
} else {
try {
userID = Integer.parseInt(parameterValue);
} catch (NumberFormatException e) {
userID = -1;
}
}
if (userID < 0) {
if (valueAllIsAllowed) {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_NAT_NUMBER_OR_ALL);
} else {
responder.writeErrorMessage(ErrorMessage.ENOUSERID_NOT_NAT_NUMBER);
}
return userID;
}
return userID;
}
/**
* Returns the parsed number or -1 if parameter is invalid (missing or not a natural number)
* and will then response to request with error message.
* @param parameters map with url parameters from client
* @param name the name of the parameter
* @param eMissing the corresponding ErrorMessage to the parameter if parameter is missing
* @param eNotNaturalNumber the corresponding ErrorMessage to the parameter if parameter is not a natural number
* @return Returns the parsed number or -1 if parameter is invalid (missing or not a natural number)
* @throws IOException Thrown if error message sending fails
*/
private int extractNaturalIntParameter(Map<String, List<String>> parameters, String name,
ErrorMessage eMissing, ErrorMessage eNotNaturalNumber)
throws IOException {
int param;
if (!parameters.containsKey(name) || parameters.get(name).get(0) == null) {
responder.writeErrorMessage(eMissing);
return -1;
}
try {
param = Integer.parseInt(parameters.get(name).get(0));
} catch (NumberFormatException e) {
param = -1;
}
if (param < 0) {
responder.writeErrorMessage(eNotNaturalNumber);
return -1;
}
return param;
}
}
| handleUpdateUser will now after the update retrieve the newest user data from the database and send the retrieved data to the client.
| src/de/tourenplaner/server/PrivateHandler.java | handleUpdateUser will now after the update retrieve the newest user data from the database and send the retrieved data to the client. |
|
Java | bsd-2-clause | 6182dbaced65243b7c7fac147d3b69e90f10496b | 0 | chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio | package jmetest.renderer.loader;
import com.jme.app.SimpleGame;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.model.XMLparser.SAXReader;
import com.jme.scene.model.XMLparser.XMLWriter;
import com.jme.scene.Node;
import java.io.*;
/**
*
* Test class for XML loading/writting with jME
* Started Date: May 30, 2004
* @author Jack Lindamood
*/
public class TestXMLLoader extends SimpleGame{
public static void main(String[] args){
new TestXMLLoader().start();
}
protected void simpleInitGame() {
lightState.get(0).setSpecular(new ColorRGBA(1,1,1,1));
SAXReader r=new SAXReader();
Node mi1=null;
try {
mi1=r.loadXML(new File("data/XML docs/newSampleScene.xml").toURL().openStream());
} catch (IOException e) {
System.out.println("bad File exception" + e.getCause() + "*" + e.getMessage());
}
// rootNode.attachChild(mi1);
ByteArrayOutputStream BO=new ByteArrayOutputStream();
XMLWriter rr=new XMLWriter(BO);
try {
rr.writeScene(mi1);
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(BO);
r.loadXML(new ByteArrayInputStream(BO.toByteArray()));
Node mi2=r.fetchCopy();
rootNode.attachChild(mi2);
}
}
| src/jmetest/renderer/loader/TestXMLLoader.java | package jmetest.renderer.loader;
import com.jme.app.SimpleGame;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.model.XMLparser.SAXReader;
import com.jme.scene.model.XMLparser.XMLWriter;
import com.jme.scene.Node;
import java.io.*;
/**
*
* Test class for XML loading/writting with jME
* Started Date: May 30, 2004
* @author Jack Lindamood
*/
public class TestXMLLoader extends SimpleGame{
public static void main(String[] args){
new TestXMLLoader().start();
}
protected void simpleInitGame() {
lightState.get(0).setSpecular(new ColorRGBA(1,1,1,1));
SAXReader r=new SAXReader();
try {
r.loadXML(new File("CVS root/data/XML docs/newSampleScene.xml").toURL().openStream());
} catch (IOException e) {
System.out.println("bad File exception" + e.getCause() + "*" + e.getMessage());
}
Node mi1=r.fetchCopy();
// rootNode.attachChild(mi1);
ByteArrayOutputStream BO=new ByteArrayOutputStream();
XMLWriter rr=new XMLWriter(BO);
try {
rr.writeScene(mi1);
} catch (IOException e) {
e.printStackTrace();
}
r.loadXML(new ByteArrayInputStream(BO.toByteArray()));
Node mi2=r.fetchCopy();
rootNode.attachChild(mi2);
System.out.print(BO);
}
}
| Cleaned up the test class.
git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@1198 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
| src/jmetest/renderer/loader/TestXMLLoader.java | Cleaned up the test class. |
|
Java | bsd-3-clause | a8f835cd8bd68da04454badcac738462adf860c8 | 0 | apptentive/apptentive-android | /*
* Copyright (c) 2016, Apptentive, Inc. All Rights Reserved.
* Please refer to the LICENSE file for the terms and conditions
* under which redistribution and use of this file is permitted.
*/
package com.apptentive.android.sdk.module.engagement.interaction.view.survey;
import android.content.Context;
import android.support.v7.view.ContextThemeWrapper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.apptentive.android.sdk.ApptentiveInternal;
import com.apptentive.android.sdk.R;
import com.apptentive.android.sdk.module.survey.OnSurveyQuestionAnsweredListener;
import com.apptentive.android.sdk.module.engagement.interaction.model.survey.Question;
abstract public class BaseSurveyQuestionView<Q extends Question> extends FrameLayout implements SurveyQuestionView {
protected Q question;
private OnSurveyQuestionAnsweredListener listener;
protected View requiredView;
protected View dashView;
protected TextView instructionsView;
protected final Context contextThemeWrapper;
protected final LayoutInflater inflater;
private View validationFailedBorder;
protected BaseSurveyQuestionView(Context context, Q question) {
super(context);
this.question = question;
contextThemeWrapper = new ContextThemeWrapper(context, ApptentiveInternal.getApptentiveTheme(context));
inflater = LayoutInflater.from(contextThemeWrapper);
inflater.inflate(R.layout.apptentive_survey_question_base, this);
requiredView = findViewById(R.id.question_required);
dashView = findViewById(R.id.question_dash);
instructionsView = (TextView) findViewById(R.id.question_instructions);
TextView title = (TextView) findViewById(R.id.question_title);
title.setText(question.getValue());
String instructionsText = question.getInstructions();
setInstructions(instructionsText);
validationFailedBorder = findViewById(R.id.validation_failed_border);
}
protected void setInstructions(String instructionsText) {
boolean hasInstructions = !TextUtils.isEmpty(instructionsText);
requiredView = findViewById(R.id.question_required);
if (question.isRequired()) {
requiredView.setVisibility(View.VISIBLE);
} else {
requiredView.setVisibility(View.GONE);
}
if (question.isRequired() && hasInstructions) {
dashView.setVisibility(View.VISIBLE);
} else {
dashView.setVisibility(View.GONE);
}
if (hasInstructions) {
instructionsView.setText(instructionsText);
instructionsView.setVisibility(View.VISIBLE);
} else {
instructionsView.setVisibility(View.GONE);
}
}
protected LinearLayout getAnswerContainer() {
return (LinearLayout) findViewById(R.id.answer_container);
}
/**
* Always call this when the answer value changes.
*/
protected void fireListener() {
if (listener != null) {
listener.onAnswered(this);
}
}
public void updateValidationState(boolean valid) {
if (valid) {
validationFailedBorder.setVisibility(View.INVISIBLE);
} else {
validationFailedBorder.setVisibility(View.VISIBLE);
}
}
@Override
public void setOnSurveyQuestionAnsweredListener(OnSurveyQuestionAnsweredListener listener) {
this.listener = listener;
}
@Override
public String getQuestionId() {
return (String) getTag(R.id.apptentive_survey_question_id);
}
@Override
public void setQuestionId(String questionId) {
setTag(R.id.apptentive_survey_question_id, questionId);
}
public abstract boolean isValid();
public abstract Object getAnswer();
}
| apptentive/src/main/java/com/apptentive/android/sdk/module/engagement/interaction/view/survey/BaseSurveyQuestionView.java | /*
* Copyright (c) 2016, Apptentive, Inc. All Rights Reserved.
* Please refer to the LICENSE file for the terms and conditions
* under which redistribution and use of this file is permitted.
*/
package com.apptentive.android.sdk.module.engagement.interaction.view.survey;
import android.content.Context;
import android.support.v7.view.ContextThemeWrapper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.apptentive.android.sdk.ApptentiveInternal;
import com.apptentive.android.sdk.R;
import com.apptentive.android.sdk.module.survey.OnSurveyQuestionAnsweredListener;
import com.apptentive.android.sdk.module.engagement.interaction.model.survey.Question;
abstract public class BaseSurveyQuestionView<Q extends Question> extends FrameLayout implements SurveyQuestionView {
protected Q question;
private OnSurveyQuestionAnsweredListener listener;
protected View requiredView;
protected View dashView;
protected TextView instructionsView;
protected final Context contextThemeWrapper;
protected final LayoutInflater inflater;
private View validationFailedBorder;
protected BaseSurveyQuestionView(Context context, Q question) {
super(context);
this.question = question;
contextThemeWrapper = new ContextThemeWrapper(context, ApptentiveInternal.apptentiveTheme);
inflater = LayoutInflater.from(contextThemeWrapper);
inflater.inflate(R.layout.apptentive_survey_question_base, this);
requiredView = findViewById(R.id.question_required);
dashView = findViewById(R.id.question_dash);
instructionsView = (TextView) findViewById(R.id.question_instructions);
TextView title = (TextView) findViewById(R.id.question_title);
title.setText(question.getValue());
String instructionsText = question.getInstructions();
setInstructions(instructionsText);
validationFailedBorder = findViewById(R.id.validation_failed_border);
}
protected void setInstructions(String instructionsText) {
boolean hasInstructions = !TextUtils.isEmpty(instructionsText);
requiredView = findViewById(R.id.question_required);
if (question.isRequired()) {
requiredView.setVisibility(View.VISIBLE);
} else {
requiredView.setVisibility(View.GONE);
}
if (question.isRequired() && hasInstructions) {
dashView.setVisibility(View.VISIBLE);
} else {
dashView.setVisibility(View.GONE);
}
if (hasInstructions) {
instructionsView.setText(instructionsText);
instructionsView.setVisibility(View.VISIBLE);
} else {
instructionsView.setVisibility(View.GONE);
}
}
protected LinearLayout getAnswerContainer() {
return (LinearLayout) findViewById(R.id.answer_container);
}
/**
* Always call this when the answer value changes.
*/
protected void fireListener() {
if (listener != null) {
listener.onAnswered(this);
}
}
public void updateValidationState(boolean valid) {
if (valid) {
validationFailedBorder.setVisibility(View.INVISIBLE);
} else {
validationFailedBorder.setVisibility(View.VISIBLE);
}
}
@Override
public void setOnSurveyQuestionAnsweredListener(OnSurveyQuestionAnsweredListener listener) {
this.listener = listener;
}
@Override
public String getQuestionId() {
return (String) getTag(R.id.apptentive_survey_question_id);
}
@Override
public void setQuestionId(String questionId) {
setTag(R.id.apptentive_survey_question_id, questionId);
}
public abstract boolean isValid();
public abstract Object getAnswer();
}
| Resolve merge conflict
| apptentive/src/main/java/com/apptentive/android/sdk/module/engagement/interaction/view/survey/BaseSurveyQuestionView.java | Resolve merge conflict |
|
Java | mit | 2a39cb7d4318ffc7dffa12675c3a340d271b0908 | 0 | CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab | package org.xcolab.view.pages.loginregister;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.HttpClientErrorException;
import org.xcolab.client.admin.attributes.configuration.ConfigurationAttributeKey;
import org.xcolab.client.admin.attributes.platform.PlatformAttributeKey;
import org.xcolab.client.members.MembersClient;
import org.xcolab.client.members.pojo.Member;
import org.xcolab.client.sharedcolab.SharedColabClient;
import org.xcolab.client.tracking.TrackingClient;
import org.xcolab.client.tracking.pojo.Location;
import org.xcolab.util.CountryUtil;
import org.xcolab.util.html.HtmlUtil;
import org.xcolab.view.auth.MemberAuthUtil;
import org.xcolab.util.i18n.I18nUtils;
import org.xcolab.view.i18n.ResourceMessageResolver;
import org.xcolab.view.pages.loginregister.exception.UserLocationNotResolvableException;
import org.xcolab.view.pages.loginregister.singlesignon.SSOKeys;
import org.xcolab.view.util.entity.ReCaptchaUtils;
import org.xcolab.view.util.entity.portlet.RequestParamUtil;
import org.xcolab.view.util.entity.portlet.session.SessionErrors;
import org.xcolab.view.util.entity.portlet.session.SessionMessages;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
@Controller
public class LoginRegisterController {
private static final Logger _log = LoggerFactory.getLogger(LoginRegisterController.class);
public static final String SSO_TARGET_KEY = "SSO_TARGET_KEY";
public static final String SSO_TARGET_REGISTRATION = "SSO_TARGET_REGISTRATION";
public static final String SSO_TARGET_LOGIN = "SSO_TARGET_LOGIN";
public static final String PRE_LOGIN_REFERRER_KEY = "PRE_LOGIN_REFERRER_KEY";
private static final String USER_NAME_REGEX = "^[a-zA-Z0-9]+$";
private static final String REGISTER_VIEW_NAME = "loginregister/register";
private final LoginRegisterService loginRegisterService;
@Autowired
ResourceMessageResolver resourceMessageResolver;
@Autowired
public LoginRegisterController(LoginRegisterService loginRegisterService) {
this.loginRegisterService = loginRegisterService;
}
// @Autowired
// private Validator validator;
//
// @InitBinder("createUserBean")
// public void initBinder(WebDataBinder binder) {
// binder.setValidator(validator);
// }
@GetMapping("/register")
public String register(HttpServletRequest request, HttpServletResponse response, Model model) {
String redirect = RequestParamUtil.getString(request, "redirect");
if (redirect == null || redirect.trim().isEmpty()) {
redirect = request.getParameter("redirect");
if (redirect == null) {
HttpSession session = request.getSession();
redirect = (String) session.getAttribute(LoginRegisterController.PRE_LOGIN_REFERRER_KEY);
}
if (redirect == null) {
redirect = request.getHeader(HttpHeaders.REFERER);
}
}
if (MemberAuthUtil.getMemberId(request) > 0) {
return "redirect:/";
}
if (StringUtils.isNotEmpty(redirect)) {
//TODO: or escape?
model.addAttribute("redirect", redirect);
}
// append SSO attributes
CreateUserBean userBean = new CreateUserBean();
getSSOUserInfo(request.getSession(), userBean);
model.addAttribute("createUserBean", userBean);
String fbIdString =
(String) request.getSession().getAttribute(SSOKeys.FACEBOOK_USER_ID);
String googleId = (String) request.getSession().getAttribute(SSOKeys.SSO_GOOGLE_ID);
if ((StringUtils.isNotBlank(fbIdString) || googleId != null)) {
model.addAttribute("isSsoLogin", true);
}
// Get country location
if (StringUtils.isEmpty(userBean.getCountry())) {
try {
userBean.setLanguage(I18nUtils.DEFAULT_LOCALE.getLanguage());
userBean.setCountry(getCountryCodeFromRemoteAddress(request.getRemoteAddr()));
} catch (UserLocationNotResolvableException ignored) {
}
}
model.addAttribute("generateScreenName", ConfigurationAttributeKey.GENERATE_SCREEN_NAME.get());
final String loginInfoText = ConfigurationAttributeKey.LOGIN_INFO_MESSAGE.get();
model.addAttribute("hasLoginInfoText", StringUtils.isNotBlank(loginInfoText));
model.addAttribute("loginInfoText", loginInfoText);
model.addAttribute("countrySelectItems", CountryUtil.getSelectOptions());
model.addAttribute("isI18NActive",ConfigurationAttributeKey.IS_I18N_ACTIVE.get());
model.addAttribute("languageSelectItems", I18nUtils.getSelectList());
return REGISTER_VIEW_NAME;
}
private String getCountryCodeFromRemoteAddress(String ipAddr) throws UserLocationNotResolvableException {
try {
Location location = TrackingClient.getLocationForIp(ipAddr);
if (location != null) {
return location.getCountry();
}
} catch (Exception e) {
throw new UserLocationNotResolvableException(
String.format("Could not retrieve country from IP address %s", ipAddr), e);
}
throw new UserLocationNotResolvableException(
String.format("Could not retrieve country from IP address %s", ipAddr));
}
public static void getSSOUserInfo(HttpSession session, CreateUserBean createUserBean) {
// append SSO attributes from session
String fbIdString =
(String) session.getAttribute(SSOKeys.FACEBOOK_USER_ID);
String googleId = (String) session.getAttribute(SSOKeys.SSO_GOOGLE_ID);
String firstName =
(String) session.getAttribute(SSOKeys.SSO_FIRST_NAME);
session.removeAttribute(SSOKeys.SSO_FIRST_NAME);
String lastName = (String) session.getAttribute(SSOKeys.SSO_LAST_NAME);
session.removeAttribute(SSOKeys.SSO_LAST_NAME);
String eMail = (String) session.getAttribute(SSOKeys.SSO_EMAIL);
session.removeAttribute(SSOKeys.SSO_EMAIL);
String screenName =
(String) session.getAttribute(SSOKeys.SSO_SCREEN_NAME);
session.removeAttribute(SSOKeys.SSO_SCREEN_NAME);
String imageId =
(String) session.getAttribute(SSOKeys.SSO_PROFILE_IMAGE_ID);
session.removeAttribute(SSOKeys.SSO_PROFILE_IMAGE_ID);
String country = (String) session.getAttribute(SSOKeys.SSO_COUNTRY);
session.removeAttribute(SSOKeys.SSO_COUNTRY);
if ((StringUtils.isNotBlank(fbIdString) || googleId != null)) {
createUserBean.setFirstName(firstName);
createUserBean.setLastName(lastName);
createUserBean.setEmail(eMail);
createUserBean.setScreenName(screenName);
createUserBean.setImageId(imageId);
createUserBean.setCaptchaNeeded(false);
}
if (StringUtils.isNotEmpty(country)) {
createUserBean.setCountry(country);
}
}
@PostMapping("/register")
public String registerUser(HttpServletRequest request, HttpServletResponse response, Model model,
@Valid CreateUserBean newAccountBean, BindingResult result,
@RequestParam(required = false) String redirect) throws IOException {
HttpSession session = request.getSession();
String fbIdString = (String) session.getAttribute(SSOKeys.FACEBOOK_USER_ID);
String googleId = (String) session.getAttribute(SSOKeys.SSO_GOOGLE_ID);
if (result.hasErrors()) {
return showRegistrationError(model);
}
boolean captchaValid = true;
// require captcha if user is not logged in via SSO
if (fbIdString == null && googleId == null
&& ConfigurationAttributeKey.GOOGLE_RECAPTCHA_IS_ACTIVE.get()) {
String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
captchaValid = ReCaptchaUtils.verify(gRecaptchaResponse,
ConfigurationAttributeKey.GOOGLE_RECAPTCHA_SITE_SECRET_KEY.get());
}
if (!captchaValid) {
SessionErrors.clear(request);
result.addError(new ObjectError("createUserBean", resourceMessageResolver.getLocalizedMessage("register.form.validation.captcha.message")));
return showRegistrationError(model);
}
//TODO: improve redirect to avoid double handling
loginRegisterService.completeRegistration(request, response, newAccountBean, redirect, false);
SessionErrors.clear(request);
SessionMessages.clear(request);
return REGISTER_VIEW_NAME;
}
private String showRegistrationError(Model model) {
model.addAttribute("countrySelectItems", CountryUtil.getSelectOptions());
model.addAttribute("isI18NActive",ConfigurationAttributeKey.IS_I18N_ACTIVE.get());
model.addAttribute("languageSelectItems", I18nUtils.getSelectList());
return REGISTER_VIEW_NAME;
}
private static void setCreateUserBeanSessionVariables(CreateUserBean createUserBean,
HttpSession portletSession) {
portletSession
.setAttribute(SSOKeys.SSO_FIRST_NAME, createUserBean.getFirstName());
portletSession
.setAttribute(SSOKeys.SSO_LAST_NAME, createUserBean.getLastName());
portletSession.setAttribute(SSOKeys.SSO_EMAIL, createUserBean.getEmail());
portletSession.setAttribute(SSOKeys.SSO_SCREEN_NAME, createUserBean.getScreenName());
portletSession.setAttribute(SSOKeys.SSO_PROFILE_IMAGE_ID, createUserBean.getImageId());
portletSession.setAttribute(SSOKeys.SSO_COUNTRY, createUserBean.getCountry());
}
@PostMapping("/register/finalize")
public void updateRegistrationParameters(HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
JSONObject json = new JSONObject();
json.put("screenName", new JSONObject());
json.put("bio", new JSONObject());
String screenName = request.getParameter("screenName");
String bio = request.getParameter("bio");
Member loggedInMember = MemberAuthUtil.getMemberOrNull(request);
if (loggedInMember!= null) {
if (!loggedInMember.getScreenName().equals(screenName)) {
if (StringUtils.isNotEmpty(screenName) && SharedColabClient
.isScreenNameUsed(screenName)
&& screenName.matches(USER_NAME_REGEX)) {
loggedInMember.setScreenName(screenName);
json.getJSONObject("screenName").put("success", true);
} else {
json.getJSONObject("screenName").put("success", false);
}
}
json.getJSONObject("bio").put("success", true);
if (StringUtils.isNotEmpty(bio)) {
if (bio.length() <= 2000) {
final String baseUri = PlatformAttributeKey.COLAB_URL.get();
loggedInMember.setShortBio(HtmlUtil.cleanSome(bio, baseUri));
MembersClient.updateMember(loggedInMember);
} else {
json.getJSONObject("bio").put("success", false);
}
}
MembersClient.updateMember(loggedInMember);
}
response.getWriter().write(json.toString());
} catch (JSONException ignored) {
}
}
@ModelAttribute("recaptchaDataSiteKey")
public String getRecaptchaDataSiteKey(){
return ConfigurationAttributeKey.GOOGLE_RECAPTCHA_SITE_KEY.get();
}
@PostMapping("/api/register/generateScreenName")
public void generateScreenName(HttpServletRequest request, HttpServletResponse response)
throws IOException {
JSONObject json = new JSONObject();
final String firstName = request.getParameter("firstName");
final String lastName = request.getParameter("lastName");
try {
try {
json.put("screenName", MembersClient.generateScreenName(lastName, firstName));
json.put("success", true);
} catch (HttpClientErrorException e) {
_log.warn("Failed to generate user name ", e);
json.put("success", false);
json.put("error", e.toString());
}
} catch (JSONException ignored) {
}
response.getWriter().write(json.toString());
}
}
| view/src/main/java/org/xcolab/view/pages/loginregister/LoginRegisterController.java | package org.xcolab.view.pages.loginregister;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.HttpClientErrorException;
import org.xcolab.client.admin.attributes.configuration.ConfigurationAttributeKey;
import org.xcolab.client.admin.attributes.platform.PlatformAttributeKey;
import org.xcolab.client.members.MembersClient;
import org.xcolab.client.members.pojo.Member;
import org.xcolab.client.sharedcolab.SharedColabClient;
import org.xcolab.client.tracking.TrackingClient;
import org.xcolab.client.tracking.pojo.Location;
import org.xcolab.util.CountryUtil;
import org.xcolab.util.html.HtmlUtil;
import org.xcolab.view.auth.MemberAuthUtil;
import org.xcolab.util.i18n.I18nUtils;
import org.xcolab.view.i18n.ResourceMessageResolver;
import org.xcolab.view.pages.loginregister.exception.UserLocationNotResolvableException;
import org.xcolab.view.pages.loginregister.singlesignon.SSOKeys;
import org.xcolab.view.util.entity.ReCaptchaUtils;
import org.xcolab.view.util.entity.portlet.RequestParamUtil;
import org.xcolab.view.util.entity.portlet.session.SessionErrors;
import org.xcolab.view.util.entity.portlet.session.SessionMessages;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
@Controller
public class LoginRegisterController {
private static final Logger _log = LoggerFactory.getLogger(LoginRegisterController.class);
public static final String SSO_TARGET_KEY = "SSO_TARGET_KEY";
public static final String SSO_TARGET_REGISTRATION = "SSO_TARGET_REGISTRATION";
public static final String SSO_TARGET_LOGIN = "SSO_TARGET_LOGIN";
public static final String PRE_LOGIN_REFERRER_KEY = "PRE_LOGIN_REFERRER_KEY";
private static final String USER_NAME_REGEX = "^[a-zA-Z0-9]+$";
private static final String REGISTER_VIEW_NAME = "loginregister/register";
private final LoginRegisterService loginRegisterService;
@Autowired
ResourceMessageResolver resourceMessageResolver;
@Autowired
public LoginRegisterController(LoginRegisterService loginRegisterService) {
this.loginRegisterService = loginRegisterService;
}
// @Autowired
// private Validator validator;
//
// @InitBinder("createUserBean")
// public void initBinder(WebDataBinder binder) {
// binder.setValidator(validator);
// }
/**
* Main view displayed for contact form
*/
@GetMapping("/register")
public String register(HttpServletRequest request, HttpServletResponse response, Model model) {
String redirect = RequestParamUtil.getString(request, "redirect");
if (redirect == null || redirect.trim().isEmpty()) {
redirect = request.getParameter("redirect");
if (redirect == null) {
HttpSession session = request.getSession();
redirect = (String) session.getAttribute(LoginRegisterController.PRE_LOGIN_REFERRER_KEY);
}
if (redirect == null) {
redirect = request.getHeader(HttpHeaders.REFERER);
}
}
if (MemberAuthUtil.getMemberId(request) > 0) {
return "redirect:/";
}
if (StringUtils.isNotEmpty(redirect)) {
//TODO: or escape?
model.addAttribute("redirect", redirect);
}
// append SSO attributes
CreateUserBean userBean = new CreateUserBean();
getSSOUserInfo(request.getSession(), userBean);
model.addAttribute("createUserBean", userBean);
String fbIdString =
(String) request.getSession().getAttribute(SSOKeys.FACEBOOK_USER_ID);
String googleId = (String) request.getSession().getAttribute(SSOKeys.SSO_GOOGLE_ID);
if ((StringUtils.isNotBlank(fbIdString) || googleId != null)) {
model.addAttribute("isSsoLogin", true);
}
// Get country location
if (StringUtils.isEmpty(userBean.getCountry())) {
try {
userBean.setLanguage(I18nUtils.DEFAULT_LOCALE.getLanguage());
userBean.setCountry(getCountryCodeFromRemoteAddress(request.getRemoteAddr()));
} catch (UserLocationNotResolvableException ignored) {
}
}
model.addAttribute("generateScreenName", ConfigurationAttributeKey.GENERATE_SCREEN_NAME.get());
final String loginInfoText = ConfigurationAttributeKey.LOGIN_INFO_MESSAGE.get();
model.addAttribute("hasLoginInfoText", StringUtils.isNotBlank(loginInfoText));
model.addAttribute("loginInfoText", loginInfoText);
model.addAttribute("countrySelectItems", CountryUtil.getSelectOptions());
model.addAttribute("isI18NActive",ConfigurationAttributeKey.IS_I18N_ACTIVE.get());
model.addAttribute("languageSelectItems", I18nUtils.getSelectList());
return REGISTER_VIEW_NAME;
}
private String getCountryCodeFromRemoteAddress(String ipAddr) throws UserLocationNotResolvableException {
try {
Location location = TrackingClient.getLocationForIp(ipAddr);
if (location != null) {
return location.getCountry();
}
} catch (Exception e) {
throw new UserLocationNotResolvableException(
String.format("Could not retrieve country from IP address %s", ipAddr), e);
}
throw new UserLocationNotResolvableException(
String.format("Could not retrieve country from IP address %s", ipAddr));
}
public static void getSSOUserInfo(HttpSession session, CreateUserBean createUserBean) {
// append SSO attributes from session
String fbIdString =
(String) session.getAttribute(SSOKeys.FACEBOOK_USER_ID);
String googleId = (String) session.getAttribute(SSOKeys.SSO_GOOGLE_ID);
String firstName =
(String) session.getAttribute(SSOKeys.SSO_FIRST_NAME);
session.removeAttribute(SSOKeys.SSO_FIRST_NAME);
String lastName = (String) session.getAttribute(SSOKeys.SSO_LAST_NAME);
session.removeAttribute(SSOKeys.SSO_LAST_NAME);
String eMail = (String) session.getAttribute(SSOKeys.SSO_EMAIL);
session.removeAttribute(SSOKeys.SSO_EMAIL);
String screenName =
(String) session.getAttribute(SSOKeys.SSO_SCREEN_NAME);
session.removeAttribute(SSOKeys.SSO_SCREEN_NAME);
String imageId =
(String) session.getAttribute(SSOKeys.SSO_PROFILE_IMAGE_ID);
session.removeAttribute(SSOKeys.SSO_PROFILE_IMAGE_ID);
String country = (String) session.getAttribute(SSOKeys.SSO_COUNTRY);
session.removeAttribute(SSOKeys.SSO_COUNTRY);
if ((StringUtils.isNotBlank(fbIdString) || googleId != null)) {
createUserBean.setFirstName(firstName);
createUserBean.setLastName(lastName);
createUserBean.setEmail(eMail);
createUserBean.setScreenName(screenName);
createUserBean.setImageId(imageId);
createUserBean.setCaptchaNeeded(false);
}
if (StringUtils.isNotEmpty(country)) {
createUserBean.setCountry(country);
}
}
@PostMapping("/register")
public String registerUser(HttpServletRequest request, HttpServletResponse response, Model model,
@Valid CreateUserBean newAccountBean, BindingResult result,
@RequestParam(required = false) String redirect) throws IOException {
HttpSession session = request.getSession();
String fbIdString = (String) session.getAttribute(SSOKeys.FACEBOOK_USER_ID);
String googleId = (String) session.getAttribute(SSOKeys.SSO_GOOGLE_ID);
if (result.hasErrors()) {
return showRegistrationError(model);
}
boolean captchaValid = true;
// require captcha if user is not logged in via SSO
if (fbIdString == null && googleId == null
&& ConfigurationAttributeKey.GOOGLE_RECAPTCHA_IS_ACTIVE.get()) {
String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
captchaValid = ReCaptchaUtils.verify(gRecaptchaResponse,
ConfigurationAttributeKey.GOOGLE_RECAPTCHA_SITE_SECRET_KEY.get());
}
if (!captchaValid) {
SessionErrors.clear(request);
result.addError(new ObjectError("createUserBean", resourceMessageResolver.getLocalizedMessage("register.form.validation.captcha.message")));
return showRegistrationError(model);
}
//TODO: improve redirect to avoid double handling
loginRegisterService.completeRegistration(request, response, newAccountBean, redirect, false);
SessionErrors.clear(request);
SessionMessages.clear(request);
return REGISTER_VIEW_NAME;
}
private String showRegistrationError(Model model) {
model.addAttribute("countrySelectItems", CountryUtil.getSelectOptions());
model.addAttribute("isI18NActive",ConfigurationAttributeKey.IS_I18N_ACTIVE.get());
model.addAttribute("languageSelectItems", I18nUtils.getSelectList());
return REGISTER_VIEW_NAME;
}
private static void setCreateUserBeanSessionVariables(CreateUserBean createUserBean,
HttpSession portletSession) {
portletSession
.setAttribute(SSOKeys.SSO_FIRST_NAME, createUserBean.getFirstName());
portletSession
.setAttribute(SSOKeys.SSO_LAST_NAME, createUserBean.getLastName());
portletSession.setAttribute(SSOKeys.SSO_EMAIL, createUserBean.getEmail());
portletSession.setAttribute(SSOKeys.SSO_SCREEN_NAME, createUserBean.getScreenName());
portletSession.setAttribute(SSOKeys.SSO_PROFILE_IMAGE_ID, createUserBean.getImageId());
portletSession.setAttribute(SSOKeys.SSO_COUNTRY, createUserBean.getCountry());
}
@PostMapping("/register/finalize")
public void updateRegistrationParameters(HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
JSONObject json = new JSONObject();
json.put("screenName", new JSONObject());
json.put("bio", new JSONObject());
String screenName = request.getParameter("screenName");
String bio = request.getParameter("bio");
Member loggedInMember = MemberAuthUtil.getMemberOrNull(request);
if (loggedInMember!= null) {
if (!loggedInMember.getScreenName().equals(screenName)) {
if (StringUtils.isNotEmpty(screenName) && SharedColabClient
.isScreenNameUsed(screenName)
&& screenName.matches(USER_NAME_REGEX)) {
loggedInMember.setScreenName(screenName);
json.getJSONObject("screenName").put("success", true);
} else {
json.getJSONObject("screenName").put("success", false);
}
}
json.getJSONObject("bio").put("success", true);
if (StringUtils.isNotEmpty(bio)) {
if (bio.length() <= 2000) {
final String baseUri = PlatformAttributeKey.COLAB_URL.get();
loggedInMember.setShortBio(HtmlUtil.cleanSome(bio, baseUri));
MembersClient.updateMember(loggedInMember);
} else {
json.getJSONObject("bio").put("success", false);
}
}
MembersClient.updateMember(loggedInMember);
}
response.getWriter().write(json.toString());
} catch (JSONException ignored) {
}
}
@ModelAttribute("recaptchaDataSiteKey")
public String getRecaptchaDataSiteKey(){
return ConfigurationAttributeKey.GOOGLE_RECAPTCHA_SITE_KEY.get();
}
@PostMapping("/api/register/generateScreenName")
public void generateScreenName(HttpServletRequest request, HttpServletResponse response)
throws IOException {
JSONObject json = new JSONObject();
final String firstName = request.getParameter("firstName");
final String lastName = request.getParameter("lastName");
try {
try {
json.put("screenName", MembersClient.generateScreenName(lastName, firstName));
json.put("success", true);
} catch (HttpClientErrorException e) {
_log.warn("Failed to generate user name ", e);
json.put("success", false);
json.put("error", e.toString());
}
} catch (JSONException ignored) {
}
response.getWriter().write(json.toString());
}
}
| Remove pointless javadoc
| view/src/main/java/org/xcolab/view/pages/loginregister/LoginRegisterController.java | Remove pointless javadoc |
|
Java | mit | beba4a90d9a5de2a17edc7b74b06ba35d0753354 | 0 | matthieu-vergne/jMetal | package org.uma.jmetal.measure.impl;
import org.uma.jmetal.util.naming.DescribedEntity;
import org.uma.jmetal.util.naming.impl.SimpleDescribedEntity;
import org.uma.jmetal.measure.Measure;
import org.uma.jmetal.measure.MeasureListener;
import org.uma.jmetal.measure.PullMeasure;
import org.uma.jmetal.measure.PushMeasure;
/**
* A {@link PullPushMeasure} aims at providing both the {@link PushMeasure} and
* {@link PullMeasure} abilities into a single {@link Measure}. One could simply
* build a brand new {@link Measure} by calling
* {@link #PullPushMeasure(String, String)}, but in the case where some existing
* measures are available, he can wrap them into a {@link PullPushMeasure} by
* calling {@link #PullPushMeasure(PushMeasure, Object)} or other constructors
* taking a {@link Measure} as argument.
*
* @author Matthieu Vergne <[email protected]>
*
* @param <Value>
*/
public class PullPushMeasure<Value> implements PullMeasure<Value>,
PushMeasure<Value> {
/**
* The measure responsible of the {@link #get()} method.
*/
private final PullMeasure<Value> puller;
/**
* The {@link Measure} responsible of the {@link #register(MeasureListener)}
* and {@link #unregister(MeasureListener)} methods.
*/
private final PushMeasure<Value> pusher;
/**
* The entity responsible of the {@link #getName()} and
* {@link #getDescription()} methods, potentially the same than
* {@link #puller} or {@link #pusher}.
*/
private final DescribedEntity reference;
/**
* Create a {@link PullPushMeasure} which wraps both a {@link PullMeasure}
* and a {@link PushMeasure}. The assumption is that both {@link Measure}s
* already represent the same {@link Measure} (i.e. the same {@link Value})
* but were implemented separately. Instantiating a {@link PullPushMeasure}
* this way allows to merge them easily without creating a completely new
* measure. Don't use this constructor to merge two different
* {@link Measure}s. The last parameter is generally used to specify which
* of the two {@link Measure}s should be used for {@link #getName()} and
* {@link #getDescription()}, but you can also provide a completely new
* instance to change them.
*
* @param pull
* the {@link PullMeasure} to wrap
* @param push
* the {@link PushMeasure} to wrap
* @param reference
* the reference to use for the name and the description of this
* {@link PullPushMeasure}
*/
public PullPushMeasure(PullMeasure<Value> pull, PushMeasure<Value> push,
DescribedEntity reference) {
this.puller = pull;
this.pusher = push;
this.reference = reference;
}
/**
* Equivalent to
* {@link #PullPushMeasure(PullMeasure, PushMeasure, DescribedEntity)} but
* the reference parameter is replaced by the specific name and description
* that you want to provide. This is a shortcut to the creation of the
* {@link DescribedEntity} instance followed by the call of the
* reference-based method.
*
* @param pull
* the {@link PullMeasure} to wrap
* @param push
* the {@link PushMeasure} to wrap
* @param name
* the name of the {@link PullPushMeasure}
* @param description
* the description of the {@link PullPushMeasure}
*/
public PullPushMeasure(PullMeasure<Value> pull, PushMeasure<Value> push,
String name, String description) {
this(pull, push, new SimpleDescribedEntity(name, description));
}
/**
* Create a {@link PullPushMeasure} which wraps a {@link PushMeasure}. The
* {@link PullMeasure} ability corresponds the storage of the {@link Value}
* pushed by the {@link PushMeasure} in order to retrieve it on demand
* through {@link PullMeasure#get()}. The name and the description of the
* {@link PullPushMeasure} are the ones provided by the wrapped
* {@link PushMeasure}.
*
* @param push
* the {@link PushMeasure} to wraps
* @param initialValue
* the {@link Value} to return before the next notification of
* the {@link PushMeasure}
*/
public PullPushMeasure(PushMeasure<Value> push, Value initialValue) {
this(new MeasureFactory().createPullFromPush(push, initialValue), push,
push);
}
/**
* Create a {@link PullPushMeasure} from scratch.
*
* @param name
* the name of the {@link PullPushMeasure}
* @param description
* the description of the {@link PullPushMeasure}
*/
public PullPushMeasure(String name, String description) {
/*
* FIXME No way to access the newly created push measure. Probably
* enclosing existing measures and creating a new one are conceptually
* incompatible (the source of push is different) and so should not be
* together in the same class.
*/
this(new SimplePushMeasure<Value>(name, description), null);
}
@Override
public void register(MeasureListener<Value> listener) {
pusher.register(listener);
}
@Override
public void unregister(MeasureListener<Value> listener) {
pusher.unregister(listener);
}
@Override
public Value get() {
return puller.get();
}
@Override
public String getName() {
return reference.getName();
}
@Override
public String getDescription() {
return reference.getDescription();
}
}
| jmetal-core/src/main/java/org/uma/jmetal/measure/impl/PullPushMeasure.java | package org.uma.jmetal.measure.impl;
import org.uma.jmetal.util.naming.DescribedEntity;
import org.uma.jmetal.util.naming.impl.SimpleDescribedEntity;
import org.uma.jmetal.measure.Measure;
import org.uma.jmetal.measure.MeasureListener;
import org.uma.jmetal.measure.PullMeasure;
import org.uma.jmetal.measure.PushMeasure;
/**
* A {@link PullPushMeasure} aims at providing both the {@link PushMeasure} and
* {@link PullMeasure} abilities into a single {@link Measure}. One could simply
* build a brand new {@link Measure} by calling
* {@link #PullPushMeasure(String, String)}, but in the case where some existing
* measures are available, he can wrap them into a {@link PullPushMeasure} by
* calling {@link #PullPushMeasure(PushMeasure, Object)} or other constructors
* taking a {@link Measure} as argument.
*
* @author Matthieu Vergne <[email protected]>
*
* @param <Value>
*/
public class PullPushMeasure<Value> implements PullMeasure<Value>,
PushMeasure<Value> {
/**
* The measure responsible of the {@link #get()} method.
*/
private final PullMeasure<Value> puller;
/**
* The {@link Measure} responsible of the {@link #register(MeasureListener)}
* and {@link #unregister(MeasureListener)} methods.
*/
private final PushMeasure<Value> pusher;
/**
* The entity responsible of the {@link #getName()} and
* {@link #getDescription()} methods, potentially the same than
* {@link #puller} or {@link #pusher}.
*/
private final DescribedEntity reference;
/**
* Create a {@link PullPushMeasure} which wraps both a {@link PullMeasure}
* and a {@link PushMeasure}. The assumption is that both {@link Measure}s
* already represent the same {@link Measure} (i.e. the same {@link Value})
* but were implemented separately. Instantiating a {@link PullPushMeasure}
* this way allows to merge them easily without creating a completely new
* measure. Don't use this constructor to merge two different
* {@link Measure}s. The last parameter is generally used to specify which
* of the two {@link Measure}s should be used for {@link #getName()} and
* {@link #getDescription()}, but you can also provide a completely new
* instance to change them.
*
* @param pull
* the {@link PullMeasure} to wrap
* @param push
* the {@link PushMeasure} to wrap
* @param reference
* the reference to use for the name and the description of this
* {@link PullPushMeasure}
*/
public PullPushMeasure(PullMeasure<Value> pull, PushMeasure<Value> push,
DescribedEntity reference) {
this.puller = pull;
this.pusher = push;
this.reference = reference;
}
/**
* Equivalent to
* {@link #PullPushMeasure(PullMeasure, PushMeasure, DescribedEntity)} but
* the reference parameter is replaced by the specific name and description
* that you want to provide. This is a shortcut to the creation of the
* {@link DescribedEntity} instance followed by the call of the
* reference-based method.
*
* @param pull
* the {@link PullMeasure} to wrap
* @param push
* the {@link PushMeasure} to wrap
* @param name
* the name of the {@link PullPushMeasure}
* @param description
* the description of the {@link PullPushMeasure}
*/
public PullPushMeasure(PullMeasure<Value> pull, PushMeasure<Value> push,
String name, String description) {
this(pull, push, new SimpleDescribedEntity(name, description));
}
/**
* Create a {@link PullPushMeasure} which wraps a {@link PushMeasure}. The
* {@link PullMeasure} ability corresponds the storage of the {@link Value}
* pushed by the {@link PushMeasure} in order to retrieve it on demand
* through {@link PullMeasure#get()}. The name and the description of the
* {@link PullPushMeasure} are the ones provided by the wrapped
* {@link PushMeasure}.
*
* @param push
* the {@link PushMeasure} to wraps
* @param initialValue
* the {@link Value} to return before the next notification of
* the {@link PushMeasure}
*/
public PullPushMeasure(PushMeasure<Value> push, Value initialValue) {
this(new MeasureFactory().createPullFromPush(push, initialValue), push,
push);
}
/**
* Create a {@link PullPushMeasure} from scratch.
*
* @param name
* the name of the {@link PullPushMeasure}
* @param description
* the description of the {@link PullPushMeasure}
*/
public PullPushMeasure(String name, String description) {
this(new SimplePushMeasure<Value>(name, description), null);
}
@Override
public void register(MeasureListener<Value> listener) {
pusher.register(listener);
}
@Override
public void unregister(MeasureListener<Value> listener) {
pusher.unregister(listener);
}
@Override
public Value get() {
return puller.get();
}
@Override
public String getName() {
return reference.getName();
}
@Override
public String getDescription() {
return reference.getDescription();
}
}
| Add a fixme because of an issue regarding how to use the PullPushMeasaure. Probably tests would have shown this sooner, so think about testing it.
| jmetal-core/src/main/java/org/uma/jmetal/measure/impl/PullPushMeasure.java | Add a fixme because of an issue regarding how to use the PullPushMeasaure. Probably tests would have shown this sooner, so think about testing it. |
|
Java | epl-1.0 | 7a9fc1920034088d8636a986890923476c3bde7e | 0 | asupdev/asup,asupdev/asup,asupdev/asup | /**
* Copyright (c) 2012, 2014 Sme.UP and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*
* Contributors:
* Mattia Rocchi - Initial API and implementation
* Giuliano Giancristofaro - Implementation
*/
package org.asup.dk.compiler.rpj.writer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.asup.dk.compiler.QCompilationSetup;
import org.asup.dk.compiler.QCompilationUnit;
import org.asup.dk.compiler.QCompilerLinker;
import org.asup.dk.compiler.QDevelopmentKitCompilerFactory;
import org.asup.il.core.QDerived;
import org.asup.il.core.QOverlay;
import org.asup.il.core.QSpecial;
import org.asup.il.core.QSpecialElement;
import org.asup.il.core.annotation.Overlay;
import org.asup.il.data.BinaryType;
import org.asup.il.data.DatetimeType;
import org.asup.il.data.QArrayDef;
import org.asup.il.data.QBinaryDef;
import org.asup.il.data.QCharacterDef;
import org.asup.il.data.QCompoundDataTerm;
import org.asup.il.data.QDataDef;
import org.asup.il.data.QDataStruct;
import org.asup.il.data.QDataStructDef;
import org.asup.il.data.QDataStructWrapper;
import org.asup.il.data.QDataTerm;
import org.asup.il.data.QDatetimeDef;
import org.asup.il.data.QDecimalDef;
import org.asup.il.data.QEnum;
import org.asup.il.data.QFloatingDef;
import org.asup.il.data.QHexadecimalDef;
import org.asup.il.data.QIndicatorDef;
import org.asup.il.data.QMultipleAtomicDataDef;
import org.asup.il.data.QMultipleCompoundDataDef;
import org.asup.il.data.QMultipleCompoundDataTerm;
import org.asup.il.data.QMultipleDataTerm;
import org.asup.il.data.QPointerDef;
import org.asup.il.data.QScrollerDef;
import org.asup.il.data.QStrollerDef;
import org.asup.il.data.QUnaryAtomicDataDef;
import org.asup.il.data.QUnaryCompoundDataTerm;
import org.asup.il.data.QUnaryDataTerm;
import org.asup.il.data.annotation.DataDef;
import org.asup.il.data.annotation.Special;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ArrayInitializer;
import org.eclipse.jdt.core.dom.EnumConstantDeclaration;
import org.eclipse.jdt.core.dom.EnumDeclaration;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
public class JDTNamedNodeWriter extends JDTNodeWriter {
private TypeDeclaration target;
@SuppressWarnings("unchecked")
public JDTNamedNodeWriter(JDTNamedNodeWriter root, QCompilationUnit compilationUnit, QCompilationSetup compilationSetup, String name) {
super(root, compilationUnit, compilationSetup);
// Type declaration
target = getAST().newTypeDeclaration();
target.setName(getAST().newSimpleName(getCompilationUnit().normalizeTypeName(name)));
target.modifiers().add(getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
if (root == null)
getJDTCompilationUnit().types().add(target);
else
root.getTarget().bodyDeclarations().add(target);
}
@SuppressWarnings("unchecked")
public void writeFieldSerializer() {
VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment();
variable.setName(getAST().newSimpleName("serialVersionUID"));
variable.setInitializer(getAST().newNumberLiteral("1L"));
FieldDeclaration field = getAST().newFieldDeclaration(variable);
field.setType(getAST().newPrimitiveType(PrimitiveType.LONG));
field.modifiers().add(getAST().newModifier(ModifierKeyword.PRIVATE_KEYWORD));
field.modifiers().add(getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
field.modifiers().add(getAST().newModifier(ModifierKeyword.FINAL_KEYWORD));
target.bodyDeclarations().add(field);
}
@SuppressWarnings("unchecked")
public void writePublicField(QDataTerm<?> dataTerm, boolean nullInitialization) {
VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment();
variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(dataTerm.getName())));
FieldDeclaration field = getAST().newFieldDeclaration(variable);
// @DataDef
writeDataDefAnnotation(field, dataTerm.getDefinition());
// default
if (dataTerm.getDataTermType().isUnary()) {
QUnaryDataTerm<?> unaryDataTerm = (QUnaryDataTerm<?>) dataTerm;
if (unaryDataTerm.getDefault() != null && !unaryDataTerm.getDefault().isEmpty())
writeAnnotation(field, DataDef.class, "value", unaryDataTerm.getDefault());
} else {
QMultipleDataTerm<?> multipleDataTerm = (QMultipleDataTerm<?>) dataTerm;
if (multipleDataTerm.getDefault() != null && !multipleDataTerm.getDefault().isEmpty())
writeAnnotation(field, DataDef.class, "values", multipleDataTerm.getDefault());
}
// @Overlay
if (dataTerm.getFacet(QOverlay.class) != null) {
QOverlay overlay = dataTerm.getFacet(QOverlay.class);
if (dataTerm.getParent() instanceof QCompoundDataTerm) {
QCompoundDataTerm<?> compoundTerm = (QCompoundDataTerm<?>) dataTerm.getParent();
if (!getCompilationUnit().equalsTermName(compoundTerm.getName(), overlay.getName()))
writeAnnotation(field, Overlay.class, "name", overlay.getName());
if (overlay.getPosition() != null && !overlay.getPosition().equals(Overlay.NEXT))
writeAnnotation(field, Overlay.class, "position", overlay.getPosition());
} else {
writeAnnotation(field, Overlay.class, "name", overlay.getName());
if (overlay.getPosition() != null)
if (overlay.getPosition().equals(Overlay.NEXT))
throw new RuntimeException("Unexpected runtime exception: nc707256c76045");
else
writeAnnotation(field, Overlay.class, "position", overlay.getPosition());
}
}
field.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
Type type = getJavaType(dataTerm);
field.setType(type);
if (nullInitialization)
variable.setInitializer(getAST().newNullLiteral());
getTarget().bodyDeclarations().add(field);
}
@SuppressWarnings("unchecked")
public void writeInnerTerm(QDataTerm<?> dataTerm) throws IOException {
switch (dataTerm.getDataTermType()) {
case UNARY_ATOMIC:
break;
case UNARY_COMPOUND:
QUnaryCompoundDataTerm<?> unaryCompoundDataTerm = (QUnaryCompoundDataTerm<?>) dataTerm;
QCompilerLinker compilerLinker = unaryCompoundDataTerm.getFacet(QCompilerLinker.class);
if (compilerLinker == null) {
QCompilationSetup compilationSetup = QDevelopmentKitCompilerFactory.eINSTANCE.createCompilationSetup();
JDTDataStructureWriter dataStructureWriter = new JDTDataStructureWriter(this, getCompilationUnit(), compilationSetup, getCompilationUnit().normalizeTypeName(unaryCompoundDataTerm),
QDataStructWrapper.class, true);
dataStructureWriter.writeDataStructure(unaryCompoundDataTerm.getDefinition());
} else {
if (isOverridden(unaryCompoundDataTerm)) {
Class<QDataStruct> linkedClass = (Class<QDataStruct>) compilerLinker.getLinkedClass();
QCompilationSetup compilationSetup = QDevelopmentKitCompilerFactory.eINSTANCE.createCompilationSetup();
JDTDataStructureWriter dataStructureWriter = new JDTDataStructureWriter(this, getCompilationUnit(), compilationSetup, getCompilationUnit().normalizeTypeName(
unaryCompoundDataTerm), linkedClass, true);
List<QDataTerm<?>> elements = new ArrayList<QDataTerm<?>>();
for (QDataTerm<?> element : unaryCompoundDataTerm.getDefinition().getElements()) {
if (element.getFacet(QDerived.class) != null)
continue;
elements.add(element);
}
dataStructureWriter.writeElements(elements);
}
}
break;
case MULTIPLE_ATOMIC:
break;
case MULTIPLE_COMPOUND:
QMultipleCompoundDataTerm<?> multipleCompoundDataTerm = (QMultipleCompoundDataTerm<?>) dataTerm;
compilerLinker = multipleCompoundDataTerm.getFacet(QCompilerLinker.class);
if (compilerLinker == null) {
QCompilationSetup compilationSetup = QDevelopmentKitCompilerFactory.eINSTANCE.createCompilationSetup();
JDTDataStructureWriter dataStructureWriter = new JDTDataStructureWriter(this, getCompilationUnit(), compilationSetup, getCompilationUnit()
.normalizeTypeName(multipleCompoundDataTerm), QDataStructWrapper.class, true);
dataStructureWriter.writeDataStructure(multipleCompoundDataTerm.getDefinition());
} else {
if (isOverridden(multipleCompoundDataTerm)) {
Class<QDataStruct> linkedClass = (Class<QDataStruct>) compilerLinker.getLinkedClass();
QCompilationSetup compilationSetup = QDevelopmentKitCompilerFactory.eINSTANCE.createCompilationSetup();
JDTDataStructureWriter dataStructureWriter = new JDTDataStructureWriter(this, getCompilationUnit(), compilationSetup, getCompilationUnit().normalizeTypeName(
multipleCompoundDataTerm), linkedClass, true);
List<QDataTerm<?>> elements = new ArrayList<QDataTerm<?>>();
for (QDataTerm<?> element : multipleCompoundDataTerm.getDefinition().getElements()) {
if (element.getFacet(QDerived.class) != null)
continue;
elements.add(element);
}
dataStructureWriter.writeElements(elements);
}
}
break;
}
QSpecial special = dataTerm.getFacet(QSpecial.class);
if (special != null) {
EnumDeclaration enumType = getAST().newEnumDeclaration();
enumType.setName(getAST().newSimpleName(getCompilationUnit().normalizeTypeName(dataTerm) + "Enum"));
writeEnum(enumType, dataTerm);
writeImport(Special.class);
target.bodyDeclarations().add(enumType);
}
}
@SuppressWarnings("unchecked")
public void writeEnum(EnumDeclaration target, QDataTerm<?> dataTerm) {
AST ast = target.getAST();
QSpecial special = dataTerm.getFacet(QSpecial.class);
target.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
target.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
// elements
int num = 0;
if (special != null) {
for (QSpecialElement element : special.getElements()) {
EnumConstantDeclaration constantDeclaration = ast.newEnumConstantDeclaration();
constantDeclaration.setName(ast.newSimpleName(normalizeEnumName(element.getName())));
writeEnumField(constantDeclaration, element);
target.enumConstants().add(num, constantDeclaration);
num++;
}
}
// restricted
if (!dataTerm.isRestricted()) {
EnumConstantDeclaration constantDeclaration = ast.newEnumConstantDeclaration();
constantDeclaration.setName(ast.newSimpleName("OTHER"));
// QSpecialElement elemDef =
// QIntegratedLanguageCoreFactory.eINSTANCE.createSpecialElement();
// writeEnumField(constantDeclaration, elemDef);
target.enumConstants().add(num, constantDeclaration);
}
}
@SuppressWarnings("unchecked")
public void writeEnumField(EnumConstantDeclaration enumField, QSpecialElement elem) {
AST ast = enumField.getAST();
NormalAnnotation normalAnnotation = ast.newNormalAnnotation();
String name = new String("*" + enumField.getName());
if (elem.getValue() != null && !name.equals(elem.getValue())) {
normalAnnotation.setTypeName(ast.newSimpleName(Special.class.getSimpleName()));
MemberValuePair memberValuePair = ast.newMemberValuePair();
memberValuePair.setName(ast.newSimpleName("value"));
StringLiteral stringLiteral = ast.newStringLiteral();
stringLiteral.setLiteralValue(elem.getValue());
memberValuePair.setValue(stringLiteral);
normalAnnotation.values().add(memberValuePair);
enumField.modifiers().add(normalAnnotation);
}
}
public Type getJavaPrimitive(QDataTerm<?> dataTerm) {
QDataDef<?> dataDef = dataTerm.getDefinition();
Class<?> klass = dataDef.getJavaClass();
Type type = getAST().newSimpleType(getAST().newSimpleName(klass.getSimpleName()));
return type;
}
public TypeDeclaration getTarget() {
return this.target;
}
public void writeDataDefAnnotation(ASTNode node, QDataDef<?> dataDef) {
@SuppressWarnings("unchecked")
Class<? extends QDataDef<?>> klassDef = (Class<? extends QDataDef<?>>) dataDef.getClass();
if (QArrayDef.class.isAssignableFrom(klassDef)) {
QArrayDef<?> arrayDef = (QArrayDef<?>) dataDef;
if (arrayDef.getDimension() != 0)
writeAnnotation(node, DataDef.class, "dimension", arrayDef.getDimension());
writeDataDefAnnotation(node, arrayDef.getArgument());
} else if (QScrollerDef.class.isAssignableFrom(klassDef)) {
QScrollerDef<?> scrollerDef = (QScrollerDef<?>) dataDef;
if (scrollerDef.getDimension() != 0)
writeAnnotation(node, DataDef.class, "dimension", scrollerDef.getDimension());
writeDataDefAnnotation(node, scrollerDef.getArgument());
} else if (QStrollerDef.class.isAssignableFrom(klassDef)) {
QStrollerDef<?> strollerDef = (QStrollerDef<?>) dataDef;
if (strollerDef.getDimension() != 0)
writeAnnotation(node, DataDef.class, "dimension", strollerDef.getDimension());
} else if (QBinaryDef.class.isAssignableFrom(klassDef)) {
QBinaryDef binaryDef = (QBinaryDef) dataDef;
writeImport(BinaryType.class);
writeAnnotation(node, DataDef.class, "binaryType", binaryDef.getType());
}
/*
* else if(QEnumeratedDataDef.class.isAssignableFrom(klassDef)) {
* QEnumeratedDataDef<?> dataDefinition = (QEnumeratedDataDef<?>)
* dataDef;
*
* QBufferedDataDef<?> innerDataDefinition =
* dataDefinition.getArgument(); writeImport(unit,
* innerDataDefinition.getClass().getName().split("\\."));
* setElementAnnotation(unit, target, innerDataDefinition);
*
* }
*/
else if (QDataStructDef.class.isAssignableFrom(klassDef)) {
QDataStructDef dataStructureDef = (QDataStructDef) dataDef;
if (dataStructureDef.isQualified())
writeAnnotation(node, DataDef.class, "qualified", dataStructureDef.isQualified());
if (dataStructureDef.getLength() > 0)
writeAnnotation(node, DataDef.class, "length", dataStructureDef.getLength());
} else if (QCharacterDef.class.isAssignableFrom(klassDef)) {
QCharacterDef charDef = (QCharacterDef) dataDef;
if (charDef.getLength() > 0)
writeAnnotation(node, DataDef.class, "length", charDef.getLength());
if (charDef.isVarying())
writeAnnotation(node, DataDef.class, "varying", charDef.isVarying());
} else if (QIndicatorDef.class.isAssignableFrom(klassDef)) {
QIndicatorDef indicatorDef = (QIndicatorDef) dataDef;
indicatorDef.toString();
} else if (QPointerDef.class.isAssignableFrom(klassDef)) {
QPointerDef pointerDef = (QPointerDef) dataDef;
pointerDef.toString();
} else if (QDatetimeDef.class.isAssignableFrom(klassDef)) {
QDatetimeDef datetimeDef = (QDatetimeDef) dataDef;
writeImport(DatetimeType.class);
writeAnnotation(node, DataDef.class, "datetimeType", datetimeDef.getType());
if (datetimeDef.getFormat() != null)
writeAnnotation(node, DataDef.class, "datetimeFormat", datetimeDef.getFormat());
} else if (QDecimalDef.class.isAssignableFrom(klassDef)) {
QDecimalDef decimalDef = (QDecimalDef) dataDef;
if (decimalDef.getPrecision() > 0)
writeAnnotation(node, DataDef.class, "precision", decimalDef.getPrecision());
if (decimalDef.getScale() > 0)
writeAnnotation(node, DataDef.class, "scale", decimalDef.getScale());
} else if (QHexadecimalDef.class.isAssignableFrom(klassDef)) {
QHexadecimalDef hexadecimalDef = (QHexadecimalDef) dataDef;
if (hexadecimalDef.getLength() > 0)
writeAnnotation(node, DataDef.class, "length", hexadecimalDef.getLength());
} else if (QFloatingDef.class.isAssignableFrom(klassDef)) {
// QFloatingDef floatDef = (QFloatingDef) dataDef;
// if (floatDef.getLength() > 0)
// writeAnnotation(target, annotationName, "length",
// floatDef.getLength());
} else
System.err.println("Unknown field type " + dataDef);
if (!dataDef.getFormulas().isEmpty())
writeAnnotation(node, DataDef.class, "formulas", dataDef.getFormulas());
}
public void writeAnnotation(ASTNode node, Class<?> annotationKlass) {
writeAnnotation(node, annotationKlass, null, null);
}
@SuppressWarnings("unchecked")
public void writeAnnotation(ASTNode node, Class<?> annotationKlass, String key, Object value) {
writeImport(annotationKlass);
NormalAnnotation annotation = null;
if (node instanceof EnumDeclaration) {
EnumDeclaration enumDeclaration = (EnumDeclaration) node;
annotation = findAnnotation(enumDeclaration.modifiers(), annotationKlass);
if (annotation == null) {
annotation = getAST().newNormalAnnotation();
annotation.setTypeName(getAST().newName(annotationKlass.getSimpleName()));
enumDeclaration.modifiers().add(annotation);
}
} else if (node instanceof FieldDeclaration) {
FieldDeclaration field = (FieldDeclaration) node;
annotation = findAnnotation(field.modifiers(), annotationKlass);
if (annotation == null) {
annotation = getAST().newNormalAnnotation();
annotation.setTypeName(getAST().newName(annotationKlass.getSimpleName()));
field.modifiers().add(annotation);
}
} else if (node instanceof EnumConstantDeclaration) {
EnumConstantDeclaration field = (EnumConstantDeclaration) node;
annotation = findAnnotation(field.modifiers(), annotationKlass);
if (annotation == null) {
annotation = getAST().newNormalAnnotation();
annotation.setTypeName(getAST().newName(annotationKlass.getSimpleName()));
field.modifiers().add(annotation);
}
} else if (node instanceof SingleVariableDeclaration) {
SingleVariableDeclaration field = (SingleVariableDeclaration) node;
annotation = findAnnotation(field.modifiers(), annotationKlass);
if (annotation == null) {
annotation = getAST().newNormalAnnotation();
annotation.setTypeName(getAST().newName(annotationKlass.getSimpleName()));
field.modifiers().add(annotation);
}
} else
throw new RuntimeException("Unexpected runtime exception 5k43jwh45j8srkf");
if (key != null) {
MemberValuePair memberValuePair = getAST().newMemberValuePair();
memberValuePair.setName(getAST().newSimpleName(key));
if (value instanceof Number) {
memberValuePair.setValue(getAST().newNumberLiteral(value.toString()));
annotation.values().add(memberValuePair);
} else if (value instanceof Boolean) {
memberValuePair.setValue(getAST().newBooleanLiteral((boolean) value));
annotation.values().add(memberValuePair);
} else if (value instanceof String) {
StringLiteral stringLiteral = getAST().newStringLiteral();
stringLiteral.setLiteralValue((String) value);
memberValuePair.setValue(stringLiteral);
annotation.values().add(memberValuePair);
} else if (value instanceof Enum) {
Enum<?> enumValue = (Enum<?>) value;
String enumName = enumValue.getClass().getSimpleName() + "." + ((Enum<?>) value).name();
memberValuePair.setValue(getAST().newName(enumName.split("\\.")));
annotation.values().add(memberValuePair);
} else if (value instanceof List) {
List<String> listValues = (List<String>) value;
ArrayInitializer arrayInitializer = getAST().newArrayInitializer();
for (String listValue : listValues) {
StringLiteral stringLiteral = getAST().newStringLiteral();
stringLiteral.setLiteralValue(listValue);
arrayInitializer.expressions().add(stringLiteral);
}
memberValuePair.setValue(arrayInitializer);
annotation.values().add(memberValuePair);
} else
throw new RuntimeException("Unexpected runtime exception k7548j4s67vo4kk");
}
}
private NormalAnnotation findAnnotation(List<?> modifiers, Class<?> annotationKlass) {
for (Object modifier : modifiers) {
if (modifier instanceof NormalAnnotation) {
NormalAnnotation annotation = (NormalAnnotation) modifier;
if (annotation.getTypeName().getFullyQualifiedName().equals(annotationKlass.getSimpleName()))
return annotation;
}
}
return null;
}
@SuppressWarnings({ "unchecked" })
public Type getJavaType(QDataTerm<?> dataTerm) {
QDataDef<?> dataDef = dataTerm.getDefinition();
writeImport(dataDef.getDataClass());
Type type = null;
switch (dataTerm.getDataTermType()) {
case MULTIPLE_ATOMIC:
QMultipleAtomicDataDef<?> multipleAtomicDataDef = (QMultipleAtomicDataDef<?>) dataDef;
QUnaryAtomicDataDef<?> innerDataDefinition = multipleAtomicDataDef.getArgument();
writeImport(innerDataDefinition.getDataClass());
Type array = getAST().newSimpleType(getAST().newSimpleName(multipleAtomicDataDef.getDataClass().getSimpleName()));
ParameterizedType parType = getAST().newParameterizedType(array);
String argument = innerDataDefinition.getDataClass().getSimpleName();
parType.typeArguments().add(getAST().newSimpleType(getAST().newSimpleName(argument)));
type = parType;
break;
case UNARY_ATOMIC:
type = getAST().newSimpleType(getAST().newSimpleName(dataDef.getDataClass().getSimpleName()));
break;
case MULTIPLE_COMPOUND:
QMultipleCompoundDataTerm<?> multipleCompoundDataTerm = (QMultipleCompoundDataTerm<?>) dataTerm;
QMultipleCompoundDataDef<?> multipleCompoundDataDef = multipleCompoundDataTerm.getDefinition();
writeImport(multipleCompoundDataDef.getDataClass());
QCompilerLinker compilerLinker = dataTerm.getFacet(QCompilerLinker.class);
compilerLinker = dataTerm.getFacet(QCompilerLinker.class);
if (compilerLinker != null) {
Class<QDataStruct> linkedClass = (Class<QDataStruct>) compilerLinker.getLinkedClass();
if (isOverridden(multipleCompoundDataTerm)) {
String qualifiedName = getCompilationUnit().getQualifiedName(dataTerm);
// TODO setup
type = getAST().newSimpleType(getAST().newName(getCompilationUnit().normalizeTypeName(qualifiedName).split("\\.")));
} else
type = getAST().newSimpleType(getAST().newName(linkedClass.getName().split("\\.")));
} else {
String qualifiedName = getCompilationUnit().getQualifiedName(dataTerm);
// TODO setup
type = getAST().newSimpleType(getAST().newName(getCompilationUnit().normalizeTypeName(qualifiedName).split("\\.")));
}
array = getAST().newSimpleType(getAST().newSimpleName(multipleCompoundDataDef.getDataClass().getSimpleName()));
parType = getAST().newParameterizedType(array);
argument = multipleCompoundDataDef.getDataClass().getSimpleName();
parType.typeArguments().add(type);
type = parType;
break;
case UNARY_COMPOUND:
QUnaryCompoundDataTerm<?> unaryCompoundDataTerm = (QUnaryCompoundDataTerm<?>) dataTerm;
compilerLinker = dataTerm.getFacet(QCompilerLinker.class);
if (compilerLinker != null) {
Class<QDataStruct> linkedClass = (Class<QDataStruct>) compilerLinker.getLinkedClass();
if (isOverridden(unaryCompoundDataTerm)) {
String qualifiedName = getCompilationUnit().getQualifiedName(dataTerm);
// TODO setup
type = getAST().newSimpleType(getAST().newName(getCompilationUnit().normalizeTypeName(qualifiedName).split("\\.")));
} else
type = getAST().newSimpleType(getAST().newName(linkedClass.getName().split("\\.")));
} else {
String qualifiedName = getCompilationUnit().getQualifiedName(dataTerm);
// TODO setup
type = getAST().newSimpleType(getAST().newName(getCompilationUnit().normalizeTypeName(qualifiedName).split("\\.")));
}
break;
}
QSpecial special = dataTerm.getFacet(QSpecial.class);
if (special != null) {
writeImport(QEnum.class);
Type enumerator = getAST().newSimpleType(getAST().newSimpleName(QEnum.class.getSimpleName()));
ParameterizedType parEnumType = getAST().newParameterizedType(enumerator);
// E
parEnumType.typeArguments().add(getAST().newSimpleType(getAST().newSimpleName(getCompilationUnit().normalizeTypeName(dataTerm) + "Enum")));
// D
parEnumType.typeArguments().add(type);
type = parEnumType;
}
return type;
}
public boolean isOverridden(QCompoundDataTerm<?> compoundDataTerm) {
for (QDataTerm<?> element : compoundDataTerm.getDefinition().getElements())
if (element.getFacet(QDerived.class) == null)
return true;
return false;
}
public String normalizeEnumName(String s) {
switch (s) {
case "*":
s = "TERM_STAR";
break;
case "/":
s = "TERM_SLASH";
break;
case "-":
s = "TERM_MINUS";
break;
case "+":
s = "TERM_PLUS";
break;
case ".":
s = "TERM_POINT";
break;
case ",":
s = "TERM_COMMA";
break;
}
if (s.startsWith("*"))
s = s.substring(1);
if (isNumeric(s))
s = "NUM_" + s.replace(".", "_");
return s;
}
private boolean isNumeric(String s) {
try {
Double.parseDouble(s);
return true;
} catch (Exception e) {
return false;
}
}
}
| org.asup.dk.compiler.rpj/src/org/asup/dk/compiler/rpj/writer/JDTNamedNodeWriter.java | /**
* Copyright (c) 2012, 2014 Sme.UP and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*
* Contributors:
* Mattia Rocchi - Initial API and implementation
* Giuliano Giancristofaro - Implementation
*/
package org.asup.dk.compiler.rpj.writer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.asup.dk.compiler.QCompilationSetup;
import org.asup.dk.compiler.QCompilationUnit;
import org.asup.dk.compiler.QCompilerLinker;
import org.asup.dk.compiler.QDevelopmentKitCompilerFactory;
import org.asup.il.core.QDerived;
import org.asup.il.core.QOverlay;
import org.asup.il.core.QSpecial;
import org.asup.il.core.QSpecialElement;
import org.asup.il.core.annotation.Overlay;
import org.asup.il.data.BinaryType;
import org.asup.il.data.DatetimeType;
import org.asup.il.data.QArrayDef;
import org.asup.il.data.QBinaryDef;
import org.asup.il.data.QCharacterDef;
import org.asup.il.data.QCompoundDataTerm;
import org.asup.il.data.QDataDef;
import org.asup.il.data.QDataStruct;
import org.asup.il.data.QDataStructDef;
import org.asup.il.data.QDataStructWrapper;
import org.asup.il.data.QDataTerm;
import org.asup.il.data.QDatetimeDef;
import org.asup.il.data.QDecimalDef;
import org.asup.il.data.QEnum;
import org.asup.il.data.QFloatingDef;
import org.asup.il.data.QHexadecimalDef;
import org.asup.il.data.QIndicatorDef;
import org.asup.il.data.QMultipleAtomicDataDef;
import org.asup.il.data.QMultipleCompoundDataDef;
import org.asup.il.data.QMultipleCompoundDataTerm;
import org.asup.il.data.QMultipleDataTerm;
import org.asup.il.data.QPointerDef;
import org.asup.il.data.QScrollerDef;
import org.asup.il.data.QStrollerDef;
import org.asup.il.data.QUnaryAtomicDataDef;
import org.asup.il.data.QUnaryCompoundDataTerm;
import org.asup.il.data.QUnaryDataTerm;
import org.asup.il.data.annotation.DataDef;
import org.asup.il.data.annotation.Special;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ArrayInitializer;
import org.eclipse.jdt.core.dom.EnumConstantDeclaration;
import org.eclipse.jdt.core.dom.EnumDeclaration;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
public class JDTNamedNodeWriter extends JDTNodeWriter {
private TypeDeclaration target;
@SuppressWarnings("unchecked")
public JDTNamedNodeWriter(JDTNamedNodeWriter root, QCompilationUnit compilationUnit, QCompilationSetup compilationSetup, String name) {
super(root, compilationUnit, compilationSetup);
// Type declaration
target = getAST().newTypeDeclaration();
target.setName(getAST().newSimpleName(getCompilationUnit().normalizeTypeName(name)));
target.modifiers().add(getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
if (root == null)
getJDTCompilationUnit().types().add(target);
else
root.getTarget().bodyDeclarations().add(target);
}
@SuppressWarnings("unchecked")
public void writeFieldSerializer() {
VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment();
variable.setName(getAST().newSimpleName("serialVersionUID"));
variable.setInitializer(getAST().newNumberLiteral("1L"));
FieldDeclaration field = getAST().newFieldDeclaration(variable);
field.setType(getAST().newPrimitiveType(PrimitiveType.LONG));
field.modifiers().add(getAST().newModifier(ModifierKeyword.PRIVATE_KEYWORD));
field.modifiers().add(getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
field.modifiers().add(getAST().newModifier(ModifierKeyword.FINAL_KEYWORD));
target.bodyDeclarations().add(field);
}
@SuppressWarnings("unchecked")
public void writePublicField(QDataTerm<?> dataTerm, boolean nullInitialization) {
VariableDeclarationFragment variable = getAST().newVariableDeclarationFragment();
variable.setName(getAST().newSimpleName(getCompilationUnit().normalizeTermName(dataTerm.getName())));
FieldDeclaration field = getAST().newFieldDeclaration(variable);
// @DataDef
writeDataDefAnnotation(field, dataTerm.getDefinition());
// default
if (dataTerm.getDataTermType().isUnary()) {
QUnaryDataTerm<?> unaryDataTerm = (QUnaryDataTerm<?>) dataTerm;
if (unaryDataTerm.getDefault() != null && !unaryDataTerm.getDefault().isEmpty())
writeAnnotation(field, DataDef.class, "value", unaryDataTerm.getDefault());
} else {
QMultipleDataTerm<?> multipleDataTerm = (QMultipleDataTerm<?>) dataTerm;
if (multipleDataTerm.getDefault() != null && !multipleDataTerm.getDefault().isEmpty())
writeAnnotation(field, DataDef.class, "values", multipleDataTerm.getDefault());
}
// @Overlay
if (dataTerm.getFacet(QOverlay.class) != null) {
QOverlay overlay = dataTerm.getFacet(QOverlay.class);
if (dataTerm.getParent() instanceof QCompoundDataTerm) {
QCompoundDataTerm<?> compoundTerm = (QCompoundDataTerm<?>) dataTerm.getParent();
if (!getCompilationUnit().equalsTermName(compoundTerm.getName(), overlay.getName()))
writeAnnotation(field, Overlay.class, "name", overlay.getName());
if (overlay.getPosition() != null && !overlay.getPosition().equals(Overlay.NEXT))
writeAnnotation(field, Overlay.class, "position", overlay.getPosition());
} else {
writeAnnotation(field, Overlay.class, "name", overlay.getName());
if (overlay.getPosition() != null)
if (overlay.getPosition().equals(Overlay.NEXT))
throw new RuntimeException("Unexpected runtime exception: nc707256c76045");
else
writeAnnotation(field, Overlay.class, "position", overlay.getPosition());
}
}
field.modifiers().add(getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
Type type = getJavaType(dataTerm);
field.setType(type);
if (nullInitialization)
variable.setInitializer(getAST().newNullLiteral());
getTarget().bodyDeclarations().add(field);
}
@SuppressWarnings("unchecked")
public void writeInnerTerm(QDataTerm<?> dataTerm) throws IOException {
switch (dataTerm.getDataTermType()) {
case UNARY_ATOMIC:
break;
case UNARY_COMPOUND:
QUnaryCompoundDataTerm<?> unaryCompoundDataTerm = (QUnaryCompoundDataTerm<?>) dataTerm;
QCompilerLinker compilerLinker = unaryCompoundDataTerm.getFacet(QCompilerLinker.class);
if (compilerLinker == null) {
QCompilationSetup compilationSetup = QDevelopmentKitCompilerFactory.eINSTANCE.createCompilationSetup();
JDTDataStructureWriter dataStructureWriter = new JDTDataStructureWriter(this, getCompilationUnit(), compilationSetup, getCompilationUnit().normalizeTypeName(unaryCompoundDataTerm),
QDataStructWrapper.class, true);
dataStructureWriter.writeDataStructure(unaryCompoundDataTerm.getDefinition());
} else {
if (isOverridden(unaryCompoundDataTerm)) {
Class<QDataStruct> linkedClass = (Class<QDataStruct>) compilerLinker.getLinkedClass();
QCompilationSetup compilationSetup = QDevelopmentKitCompilerFactory.eINSTANCE.createCompilationSetup();
JDTDataStructureWriter dataStructureWriter = new JDTDataStructureWriter(this, getCompilationUnit(), compilationSetup, getCompilationUnit().normalizeTypeName(
unaryCompoundDataTerm), linkedClass, true);
List<QDataTerm<?>> elements = new ArrayList<QDataTerm<?>>();
for (QDataTerm<?> element : unaryCompoundDataTerm.getDefinition().getElements()) {
if (element.getFacet(QDerived.class) != null)
continue;
elements.add(element);
}
dataStructureWriter.writeElements(elements);
}
}
break;
case MULTIPLE_ATOMIC:
break;
case MULTIPLE_COMPOUND:
QMultipleCompoundDataTerm<?> multipleCompoundDataTerm = (QMultipleCompoundDataTerm<?>) dataTerm;
compilerLinker = multipleCompoundDataTerm.getFacet(QCompilerLinker.class);
if (compilerLinker == null) {
QCompilationSetup compilationSetup = QDevelopmentKitCompilerFactory.eINSTANCE.createCompilationSetup();
JDTDataStructureWriter dataStructureWriter = new JDTDataStructureWriter(this, getCompilationUnit(), compilationSetup, getCompilationUnit()
.normalizeTypeName(multipleCompoundDataTerm), QDataStructWrapper.class, true);
dataStructureWriter.writeDataStructure(multipleCompoundDataTerm.getDefinition());
} else {
if (isOverridden(multipleCompoundDataTerm)) {
Class<QDataStruct> linkedClass = (Class<QDataStruct>) compilerLinker.getLinkedClass();
QCompilationSetup compilationSetup = QDevelopmentKitCompilerFactory.eINSTANCE.createCompilationSetup();
JDTDataStructureWriter dataStructureWriter = new JDTDataStructureWriter(this, getCompilationUnit(), compilationSetup, getCompilationUnit().normalizeTypeName(
multipleCompoundDataTerm), linkedClass, true);
List<QDataTerm<?>> elements = new ArrayList<QDataTerm<?>>();
for (QDataTerm<?> element : multipleCompoundDataTerm.getDefinition().getElements()) {
if (element.getFacet(QDerived.class) != null)
continue;
elements.add(element);
}
dataStructureWriter.writeElements(elements);
}
}
break;
}
QSpecial special = dataTerm.getFacet(QSpecial.class);
if (special != null) {
EnumDeclaration enumType = getAST().newEnumDeclaration();
enumType.setName(getAST().newSimpleName(getCompilationUnit().normalizeTypeName(dataTerm) + "Enum"));
writeEnum(enumType, dataTerm);
writeImport(Special.class);
target.bodyDeclarations().add(enumType);
}
}
@SuppressWarnings("unchecked")
public void writeEnum(EnumDeclaration target, QDataTerm<?> dataTerm) {
AST ast = target.getAST();
QSpecial special = dataTerm.getFacet(QSpecial.class);
target.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
target.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
// elements
int num = 0;
if (special != null) {
for (QSpecialElement element : special.getElements()) {
EnumConstantDeclaration constantDeclaration = ast.newEnumConstantDeclaration();
constantDeclaration.setName(ast.newSimpleName(normalizeEnumName(element.getName())));
writeEnumField(constantDeclaration, element);
target.enumConstants().add(num, constantDeclaration);
num++;
}
}
// restricted
if (!dataTerm.isRestricted()) {
EnumConstantDeclaration constantDeclaration = ast.newEnumConstantDeclaration();
constantDeclaration.setName(ast.newSimpleName("OTHER"));
// QSpecialElement elemDef =
// QIntegratedLanguageCoreFactory.eINSTANCE.createSpecialElement();
// writeEnumField(constantDeclaration, elemDef);
target.enumConstants().add(num, constantDeclaration);
}
}
@SuppressWarnings("unchecked")
public void writeEnumField(EnumConstantDeclaration enumField, QSpecialElement elem) {
AST ast = enumField.getAST();
NormalAnnotation normalAnnotation = ast.newNormalAnnotation();
String name = new String("*" + enumField.getName());
if (elem.getValue() != null && !name.equals(elem.getValue())) {
normalAnnotation.setTypeName(ast.newSimpleName(Special.class.getSimpleName()));
MemberValuePair memberValuePair = ast.newMemberValuePair();
memberValuePair.setName(ast.newSimpleName("value"));
StringLiteral stringLiteral = ast.newStringLiteral();
stringLiteral.setLiteralValue(elem.getValue());
memberValuePair.setValue(stringLiteral);
normalAnnotation.values().add(memberValuePair);
enumField.modifiers().add(normalAnnotation);
}
}
public Type getJavaPrimitive(QDataTerm<?> dataTerm) {
QDataDef<?> dataDef = dataTerm.getDefinition();
Class<?> klass = dataDef.getJavaClass();
Type type = getAST().newSimpleType(getAST().newSimpleName(klass.getSimpleName()));
return type;
}
public TypeDeclaration getTarget() {
return this.target;
}
public void writeDataDefAnnotation(ASTNode node, QDataDef<?> dataDef) {
@SuppressWarnings("unchecked")
Class<? extends QDataDef<?>> klassDef = (Class<? extends QDataDef<?>>) dataDef.getClass();
if (QArrayDef.class.isAssignableFrom(klassDef)) {
QArrayDef<?> arrayDef = (QArrayDef<?>) dataDef;
if (arrayDef.getDimension() != 0)
writeAnnotation(node, DataDef.class, "dimension", arrayDef.getDimension());
writeDataDefAnnotation(node, arrayDef.getArgument());
} else if (QScrollerDef.class.isAssignableFrom(klassDef)) {
QScrollerDef<?> scrollerDef = (QScrollerDef<?>) dataDef;
if (scrollerDef.getDimension() != 0)
writeAnnotation(node, DataDef.class, "dimension", scrollerDef.getDimension());
writeDataDefAnnotation(node, scrollerDef.getArgument());
} else if (QStrollerDef.class.isAssignableFrom(klassDef)) {
QStrollerDef<?> strollerDef = (QStrollerDef<?>) dataDef;
if (strollerDef.getDimension() != 0)
writeAnnotation(node, DataDef.class, "dimension", strollerDef.getDimension());
} else if (QBinaryDef.class.isAssignableFrom(klassDef)) {
QBinaryDef binaryDef = (QBinaryDef) dataDef;
writeImport(BinaryType.class);
writeAnnotation(node, DataDef.class, "binaryType", binaryDef.getType());
}
/*
* else if(QEnumeratedDataDef.class.isAssignableFrom(klassDef)) {
* QEnumeratedDataDef<?> dataDefinition = (QEnumeratedDataDef<?>)
* dataDef;
*
* QBufferedDataDef<?> innerDataDefinition =
* dataDefinition.getArgument(); writeImport(unit,
* innerDataDefinition.getClass().getName().split("\\."));
* setElementAnnotation(unit, target, innerDataDefinition);
*
* }
*/
else if (QDataStructDef.class.isAssignableFrom(klassDef)) {
QDataStructDef dataStructureDef = (QDataStructDef) dataDef;
if (dataStructureDef.isQualified())
writeAnnotation(node, DataDef.class, "qualified", dataStructureDef.isQualified());
if (dataStructureDef.getLength() > 0)
writeAnnotation(node, DataDef.class, "length", dataStructureDef.getLength());
} else if (QCharacterDef.class.isAssignableFrom(klassDef)) {
QCharacterDef charDef = (QCharacterDef) dataDef;
if (charDef.getLength() > 0)
writeAnnotation(node, DataDef.class, "length", charDef.getLength());
if (charDef.isVarying())
writeAnnotation(node, DataDef.class, "varying", charDef.isVarying());
} else if (QIndicatorDef.class.isAssignableFrom(klassDef)) {
QIndicatorDef indicatorDef = (QIndicatorDef) dataDef;
indicatorDef.toString();
} else if (QPointerDef.class.isAssignableFrom(klassDef)) {
QPointerDef pointerDef = (QPointerDef) dataDef;
pointerDef.toString();
} else if (QDatetimeDef.class.isAssignableFrom(klassDef)) {
QDatetimeDef datetimeDef = (QDatetimeDef) dataDef;
writeImport(DatetimeType.class);
writeAnnotation(node, DataDef.class, "datetimeType", datetimeDef.getType());
if (datetimeDef.getFormat() != null)
writeAnnotation(node, DataDef.class, "datetimeFormat", datetimeDef.getFormat());
} else if (QDecimalDef.class.isAssignableFrom(klassDef)) {
QDecimalDef decimalDef = (QDecimalDef) dataDef;
if (decimalDef.getPrecision() > 0)
writeAnnotation(node, DataDef.class, "precision", decimalDef.getPrecision());
if (decimalDef.getScale() > 0)
writeAnnotation(node, DataDef.class, "scale", decimalDef.getScale());
} else if (QHexadecimalDef.class.isAssignableFrom(klassDef)) {
QHexadecimalDef hexadecimalDef = (QHexadecimalDef) dataDef;
if (hexadecimalDef.getLength() > 0)
writeAnnotation(node, DataDef.class, "length", hexadecimalDef.getLength());
} else if (QFloatingDef.class.isAssignableFrom(klassDef)) {
// QFloatingDef floatDef = (QFloatingDef) dataDef;
// if (floatDef.getLength() > 0)
// writeAnnotation(target, annotationName, "length",
// floatDef.getLength());
} else
System.err.println("Unknown field type " + dataDef);
if (!dataDef.getFormulas().isEmpty())
writeAnnotation(node, DataDef.class, "formulas", dataDef.getFormulas());
}
public void writeAnnotation(ASTNode node, Class<?> annotationKlass) {
writeAnnotation(node, annotationKlass, null, null);
}
@SuppressWarnings("unchecked")
public void writeAnnotation(ASTNode node, Class<?> annotationKlass, String key, Object value) {
writeImport(annotationKlass);
NormalAnnotation annotation = null;
if (node instanceof EnumDeclaration) {
EnumDeclaration enumDeclaration = (EnumDeclaration) node;
annotation = findAnnotation(enumDeclaration.modifiers(), annotationKlass);
if (annotation == null) {
annotation = getAST().newNormalAnnotation();
annotation.setTypeName(getAST().newName(annotationKlass.getSimpleName()));
enumDeclaration.modifiers().add(annotation);
}
} else if (node instanceof FieldDeclaration) {
FieldDeclaration field = (FieldDeclaration) node;
annotation = findAnnotation(field.modifiers(), annotationKlass);
if (annotation == null) {
annotation = getAST().newNormalAnnotation();
annotation.setTypeName(getAST().newName(annotationKlass.getSimpleName()));
field.modifiers().add(annotation);
}
} else if (node instanceof SingleVariableDeclaration) {
SingleVariableDeclaration field = (SingleVariableDeclaration) node;
annotation = findAnnotation(field.modifiers(), annotationKlass);
if (annotation == null) {
annotation = getAST().newNormalAnnotation();
annotation.setTypeName(getAST().newName(annotationKlass.getSimpleName()));
field.modifiers().add(annotation);
}
} else
throw new RuntimeException("Unexpected runtime exception 5k43jwh45j8srkf");
if (key != null) {
MemberValuePair memberValuePair = getAST().newMemberValuePair();
memberValuePair.setName(getAST().newSimpleName(key));
if (value instanceof Number) {
memberValuePair.setValue(getAST().newNumberLiteral(value.toString()));
annotation.values().add(memberValuePair);
} else if (value instanceof Boolean) {
memberValuePair.setValue(getAST().newBooleanLiteral((boolean) value));
annotation.values().add(memberValuePair);
} else if (value instanceof String) {
StringLiteral stringLiteral = getAST().newStringLiteral();
stringLiteral.setLiteralValue((String) value);
memberValuePair.setValue(stringLiteral);
annotation.values().add(memberValuePair);
} else if (value instanceof Enum) {
Enum<?> enumValue = (Enum<?>) value;
String enumName = enumValue.getClass().getSimpleName() + "." + ((Enum<?>) value).name();
memberValuePair.setValue(getAST().newName(enumName.split("\\.")));
annotation.values().add(memberValuePair);
} else if (value instanceof List) {
List<String> listValues = (List<String>) value;
ArrayInitializer arrayInitializer = getAST().newArrayInitializer();
for (String listValue : listValues) {
StringLiteral stringLiteral = getAST().newStringLiteral();
stringLiteral.setLiteralValue(listValue);
arrayInitializer.expressions().add(stringLiteral);
}
memberValuePair.setValue(arrayInitializer);
annotation.values().add(memberValuePair);
} else
throw new RuntimeException("Unexpected runtime exception k7548j4s67vo4kk");
}
}
private NormalAnnotation findAnnotation(List<?> modifiers, Class<?> annotationKlass) {
for (Object modifier : modifiers) {
if (modifier instanceof NormalAnnotation) {
NormalAnnotation annotation = (NormalAnnotation) modifier;
if (annotation.getTypeName().getFullyQualifiedName().equals(annotationKlass.getSimpleName()))
return annotation;
}
}
return null;
}
@SuppressWarnings({ "unchecked" })
public Type getJavaType(QDataTerm<?> dataTerm) {
QDataDef<?> dataDef = dataTerm.getDefinition();
writeImport(dataDef.getDataClass());
Type type = null;
switch (dataTerm.getDataTermType()) {
case MULTIPLE_ATOMIC:
QMultipleAtomicDataDef<?> multipleAtomicDataDef = (QMultipleAtomicDataDef<?>) dataDef;
QUnaryAtomicDataDef<?> innerDataDefinition = multipleAtomicDataDef.getArgument();
writeImport(innerDataDefinition.getDataClass());
Type array = getAST().newSimpleType(getAST().newSimpleName(multipleAtomicDataDef.getDataClass().getSimpleName()));
ParameterizedType parType = getAST().newParameterizedType(array);
String argument = innerDataDefinition.getDataClass().getSimpleName();
parType.typeArguments().add(getAST().newSimpleType(getAST().newSimpleName(argument)));
type = parType;
break;
case UNARY_ATOMIC:
type = getAST().newSimpleType(getAST().newSimpleName(dataDef.getDataClass().getSimpleName()));
break;
case MULTIPLE_COMPOUND:
QMultipleCompoundDataTerm<?> multipleCompoundDataTerm = (QMultipleCompoundDataTerm<?>) dataTerm;
QMultipleCompoundDataDef<?> multipleCompoundDataDef = multipleCompoundDataTerm.getDefinition();
writeImport(multipleCompoundDataDef.getDataClass());
QCompilerLinker compilerLinker = dataTerm.getFacet(QCompilerLinker.class);
compilerLinker = dataTerm.getFacet(QCompilerLinker.class);
if (compilerLinker != null) {
Class<QDataStruct> linkedClass = (Class<QDataStruct>) compilerLinker.getLinkedClass();
if (isOverridden(multipleCompoundDataTerm)) {
String qualifiedName = getCompilationUnit().getQualifiedName(dataTerm);
// TODO setup
type = getAST().newSimpleType(getAST().newName(getCompilationUnit().normalizeTypeName(qualifiedName).split("\\.")));
} else
type = getAST().newSimpleType(getAST().newName(linkedClass.getName().split("\\.")));
} else {
String qualifiedName = getCompilationUnit().getQualifiedName(dataTerm);
// TODO setup
type = getAST().newSimpleType(getAST().newName(getCompilationUnit().normalizeTypeName(qualifiedName).split("\\.")));
}
array = getAST().newSimpleType(getAST().newSimpleName(multipleCompoundDataDef.getDataClass().getSimpleName()));
parType = getAST().newParameterizedType(array);
argument = multipleCompoundDataDef.getDataClass().getSimpleName();
parType.typeArguments().add(type);
type = parType;
break;
case UNARY_COMPOUND:
QUnaryCompoundDataTerm<?> unaryCompoundDataTerm = (QUnaryCompoundDataTerm<?>) dataTerm;
compilerLinker = dataTerm.getFacet(QCompilerLinker.class);
if (compilerLinker != null) {
Class<QDataStruct> linkedClass = (Class<QDataStruct>) compilerLinker.getLinkedClass();
if (isOverridden(unaryCompoundDataTerm)) {
String qualifiedName = getCompilationUnit().getQualifiedName(dataTerm);
// TODO setup
type = getAST().newSimpleType(getAST().newName(getCompilationUnit().normalizeTypeName(qualifiedName).split("\\.")));
} else
type = getAST().newSimpleType(getAST().newName(linkedClass.getName().split("\\.")));
} else {
String qualifiedName = getCompilationUnit().getQualifiedName(dataTerm);
// TODO setup
type = getAST().newSimpleType(getAST().newName(getCompilationUnit().normalizeTypeName(qualifiedName).split("\\.")));
}
break;
}
QSpecial special = dataTerm.getFacet(QSpecial.class);
if (special != null) {
writeImport(QEnum.class);
Type enumerator = getAST().newSimpleType(getAST().newSimpleName(QEnum.class.getSimpleName()));
ParameterizedType parEnumType = getAST().newParameterizedType(enumerator);
// E
parEnumType.typeArguments().add(getAST().newSimpleType(getAST().newSimpleName(getCompilationUnit().normalizeTypeName(dataTerm) + "Enum")));
// D
parEnumType.typeArguments().add(type);
type = parEnumType;
}
return type;
}
public boolean isOverridden(QCompoundDataTerm<?> compoundDataTerm) {
for (QDataTerm<?> element : compoundDataTerm.getDefinition().getElements())
if (element.getFacet(QDerived.class) == null)
return true;
return false;
}
public String normalizeEnumName(String s) {
switch (s) {
case "*":
s = "TERM_STAR";
break;
case "/":
s = "TERM_SLASH";
break;
case "-":
s = "TERM_MINUS";
break;
case "+":
s = "TERM_PLUS";
break;
case ".":
s = "TERM_POINT";
break;
case ",":
s = "TERM_COMMA";
break;
}
if (s.startsWith("*"))
s = s.substring(1);
if (isNumeric(s))
s = "NUM_" + s.replace(".", "_");
return s;
}
private boolean isNumeric(String s) {
try {
Double.parseDouble(s);
return true;
} catch (Exception e) {
return false;
}
}
}
| Group PTF #75 | org.asup.dk.compiler.rpj/src/org/asup/dk/compiler/rpj/writer/JDTNamedNodeWriter.java | Group PTF #75 |
|
Java | lgpl-2.1 | 761064ba02b288d7485fa1b49257661e8877d9b7 | 0 | uugaa/hibernate-ogm,tempbottle/hibernate-ogm,tempbottle/hibernate-ogm,gunnarmorling/hibernate-ogm,Sanne/hibernate-ogm,mp911de/hibernate-ogm,DavideD/hibernate-ogm-contrib,ZJaffee/hibernate-ogm,tempbottle/hibernate-ogm,hibernate/hibernate-ogm,DavideD/hibernate-ogm-cassandra,Sanne/hibernate-ogm,Sanne/hibernate-ogm,jhalliday/hibernate-ogm,hibernate/hibernate-ogm,gunnarmorling/hibernate-ogm,hibernate/hibernate-ogm,uugaa/hibernate-ogm,hibernate/hibernate-ogm,emmanuelbernard/hibernate-ogm,DavideD/hibernate-ogm,ZJaffee/hibernate-ogm,hferentschik/hibernate-ogm,uugaa/hibernate-ogm,DavideD/hibernate-ogm,gunnarmorling/hibernate-ogm,schernolyas/hibernate-ogm,DavideD/hibernate-ogm-cassandra,ZJaffee/hibernate-ogm,DavideD/hibernate-ogm-contrib,schernolyas/hibernate-ogm,DavideD/hibernate-ogm,jhalliday/hibernate-ogm,DavideD/hibernate-ogm,DavideD/hibernate-ogm-cassandra,mp911de/hibernate-ogm,jhalliday/hibernate-ogm,DavideD/hibernate-ogm-contrib,mp911de/hibernate-ogm,schernolyas/hibernate-ogm,Sanne/hibernate-ogm | /*
* Hibernate OGM, Domain model persistence for NoSQL datastores
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.ogm.datastore.neo4j.impl;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Constraint;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.PrimaryKey;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.UniqueKey;
import org.hibernate.ogm.datastore.neo4j.dialect.impl.CypherCRUD;
import org.hibernate.ogm.datastore.neo4j.logging.impl.Log;
import org.hibernate.ogm.datastore.neo4j.logging.impl.LoggerFactory;
import org.hibernate.ogm.datastore.spi.DatastoreProvider;
import org.hibernate.ogm.dialect.spi.BaseSchemaDefiner;
import org.hibernate.ogm.id.spi.PersistentNoSqlIdentifierGenerator;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy;
import org.jboss.logging.Logger.Level;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.schema.ConstraintDefinition;
import org.neo4j.graphdb.schema.ConstraintType;
/**
* Initialize the schema for the Neo4j database:
* <ol>
* <li>create sequences;</li>
* <li>create unique constraints on identifiers, natural ids and unique columns</li>
* </ol>
* <p>
* Note that unique constraints involving multiple columns won't be applied because Neo4j does not support it.
* <p>
* The creation of unique constraints can be skipped setting the property
* {@link Environment#UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY} to the value
* {@link UniqueConstraintSchemaUpdateStrategy#SKIP}. Because in Neo4j unique constraints don't have a name, setting the
* value to {@link UniqueConstraintSchemaUpdateStrategy#RECREATE_QUIETLY} or
* {@link UniqueConstraintSchemaUpdateStrategy#DROP_RECREATE_QUIETLY} will have the same effect: keep the existing
* constraints and create the missing one.
*
* @author Davide D'Alto
* @author Gunnar Morling
*/
public class Neo4jSchemaDefiner extends BaseSchemaDefiner {
private static final Log log = LoggerFactory.getLogger();
@Override
public void initializeSchema(Configuration configuration, SessionFactoryImplementor factory) {
SessionFactoryImplementor sessionFactoryImplementor = factory;
ServiceRegistryImplementor registry = sessionFactoryImplementor.getServiceRegistry();
Neo4jDatastoreProvider provider = (Neo4jDatastoreProvider) registry.getService( DatastoreProvider.class );
Set<PersistentNoSqlIdentifierGenerator> sequences = getPersistentGenerators( sessionFactoryImplementor );
provider.getSequenceGenerator().createSequences( sequences );
createEntityConstraints( provider.getDataBase(), configuration );
}
public void createEntityConstraints(GraphDatabaseService neo4jDb, Configuration configuration) {
UniqueConstraintSchemaUpdateStrategy constraintMethod = UniqueConstraintSchemaUpdateStrategy.interpret( configuration.getProperties().get(
Environment.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY ) );
log.debugf( "%1$s property set to %2$s" , Environment.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY );
if ( constraintMethod == UniqueConstraintSchemaUpdateStrategy.SKIP ) {
log.tracef( "%1$s property set to %2$s: Skipping generation of unique constraints", Environment.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY, UniqueConstraintSchemaUpdateStrategy.SKIP );
}
else {
log.debug( "Creating missing constraints" );
Transaction tx = null;
try {
tx = neo4jDb.beginTx();
addUniqueConstraints( neo4jDb, configuration );
tx.success();
}
finally {
tx.close();
}
}
}
private void addUniqueConstraints(GraphDatabaseService neo4jDb, Configuration configuration) {
Iterator<Table> tableMappings = configuration.getTableMappings();
while ( tableMappings.hasNext() ) {
Table table = (Table) tableMappings.next();
if ( table.isPhysicalTable() ) {
Label label = CypherCRUD.nodeLabel( table.getName() );
PrimaryKey primaryKey = table.getPrimaryKey();
createConstraint( neo4jDb, table, label, primaryKey );
@SuppressWarnings("unchecked")
Iterator<Column> columnIterator = table.getColumnIterator();
while ( columnIterator.hasNext() ) {
Column column = columnIterator.next();
if ( column.isUnique() ) {
createUniqueConstraintIfMissing( neo4jDb, label, column.getName() );
}
}
Iterator<UniqueKey> uniqueKeyIterator = table.getUniqueKeyIterator();
while ( uniqueKeyIterator.hasNext() ) {
createConstraint( neo4jDb, table, label, uniqueKeyIterator.next() );
}
}
}
}
private void createConstraint(GraphDatabaseService neo4jDb, Table table, Label label, Constraint constraint) {
if ( constraint != null ) {
// Neo4j does not store properties representing foreign key columns, so we don't need to create unique
// constraints for them
if ( !isAppliedToForeignColumns( table, constraint ) ) {
if ( constraint.getColumnSpan() == 1 ) {
String propertyName = constraint.getColumn( 0 ).getName();
createUniqueConstraintIfMissing( neo4jDb, label, propertyName );
}
else if ( log.isEnabled( Level.WARN ) ) {
logMultipleColumnsWarning( table, constraint );
}
}
}
}
private boolean isAppliedToForeignColumns(Table table, Constraint constraint) {
List<?> constraintColumns = constraint.getColumns();
for ( Iterator<?> iterator = table.getForeignKeyIterator(); iterator.hasNext(); ) {
ForeignKey foreignKey = (ForeignKey) iterator.next();
List<?> foreignKeyColumns = foreignKey.getColumns();
for ( Object object : foreignKeyColumns ) {
if ( constraintColumns.contains( object ) ) {
// This constraint requires a foreign column
return true;
}
}
}
return false;
}
private void logMultipleColumnsWarning(Table table, Constraint constraint) {
StringBuilder builder = new StringBuilder();
for ( Iterator<Column> columnIterator = constraint.getColumnIterator(); columnIterator.hasNext(); ) {
Column column = columnIterator.next();
builder.append( ", " );
builder.append( column.getName() );
}
String columns = "[" + builder.substring( 2 ) + "]";
log.constraintSpanningMultipleColumns( constraint.getName(), table.getName(), columns );
}
private void createUniqueConstraintIfMissing(GraphDatabaseService neo4jDb, Label label, String property) {
if ( isMissingUniqueConstraint( neo4jDb, label, property ) ) {
log.tracef( "Creating unique constraint for nodes labeled as %1$s on property %2$s", label, property);
neo4jDb.schema().constraintFor( label ).assertPropertyIsUnique( property ).create();
}
else {
log.tracef( "Unique constraint already exists for nodes labeled as %1$s on property %2$s", label, property);
}
}
private boolean isMissingUniqueConstraint(GraphDatabaseService neo4jDb, Label label, String propertyName) {
Iterable<ConstraintDefinition> constraints = neo4jDb.schema().getConstraints( label );
for ( ConstraintDefinition constraint : constraints ) {
if ( constraint.isConstraintType( ConstraintType.UNIQUENESS ) ) {
for ( String propertyKey : constraint.getPropertyKeys() ) {
if ( propertyKey.equals( propertyName ) ) {
return false;
}
}
}
}
return true;
}
}
| neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/impl/Neo4jSchemaDefiner.java | /*
* Hibernate OGM, Domain model persistence for NoSQL datastores
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.ogm.datastore.neo4j.impl;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Constraint;
import org.hibernate.mapping.PrimaryKey;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.UniqueKey;
import org.hibernate.ogm.datastore.neo4j.dialect.impl.CypherCRUD;
import org.hibernate.ogm.datastore.neo4j.logging.impl.Log;
import org.hibernate.ogm.datastore.neo4j.logging.impl.LoggerFactory;
import org.hibernate.ogm.datastore.spi.DatastoreProvider;
import org.hibernate.ogm.dialect.spi.BaseSchemaDefiner;
import org.hibernate.ogm.id.spi.PersistentNoSqlIdentifierGenerator;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy;
import org.jboss.logging.Logger.Level;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.schema.ConstraintDefinition;
import org.neo4j.graphdb.schema.ConstraintType;
/**
* Initialize the schema for the Neo4j database:
* <ol>
* <li>create sequences;</li>
* <li>create unique constraints on identifiers, natural ids and unique columns</li>
* </ol>
* <p>
* Note that unique constraints involving multiple columns won't be applied because Neo4j does not support it.
* <p>
* The creation of unique constraints can be skipped setting the property
* {@link Environment#UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY} to the value
* {@link UniqueConstraintSchemaUpdateStrategy#SKIP}. Because in Neo4j unique constraints don't have a name, setting the
* value to {@link UniqueConstraintSchemaUpdateStrategy#RECREATE_QUIETLY} or
* {@link UniqueConstraintSchemaUpdateStrategy#DROP_RECREATE_QUIETLY} will have the same effect: keep the existing
* constraints and create the missing one.
*
* @author Davide D'Alto
* @author Gunnar Morling
*/
public class Neo4jSchemaDefiner extends BaseSchemaDefiner {
private static final Log log = LoggerFactory.getLogger();
@Override
public void initializeSchema(Configuration configuration, SessionFactoryImplementor factory) {
SessionFactoryImplementor sessionFactoryImplementor = factory;
ServiceRegistryImplementor registry = sessionFactoryImplementor.getServiceRegistry();
Neo4jDatastoreProvider provider = (Neo4jDatastoreProvider) registry.getService( DatastoreProvider.class );
Set<PersistentNoSqlIdentifierGenerator> sequences = getPersistentGenerators( sessionFactoryImplementor );
provider.getSequenceGenerator().createSequences( sequences );
createEntityConstraints( provider.getDataBase(), configuration );
}
public void createEntityConstraints(GraphDatabaseService neo4jDb, Configuration configuration) {
UniqueConstraintSchemaUpdateStrategy constraintMethod = UniqueConstraintSchemaUpdateStrategy.interpret( configuration.getProperties().get(
Environment.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY ) );
log.debugf( "%1$s property set to %2$s" , Environment.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY );
if ( constraintMethod == UniqueConstraintSchemaUpdateStrategy.SKIP ) {
log.tracef( "%1$s property set to %2$s: Skipping generation of unique constraints", Environment.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY, UniqueConstraintSchemaUpdateStrategy.SKIP );
}
else {
log.debug( "Creating missing constraints" );
Transaction tx = null;
try {
tx = neo4jDb.beginTx();
addUniqueConstraints( neo4jDb, configuration );
tx.success();
}
finally {
tx.close();
}
}
}
private void addUniqueConstraints(GraphDatabaseService neo4jDb, Configuration configuration) {
Iterator<Table> tableMappings = configuration.getTableMappings();
while ( tableMappings.hasNext() ) {
Table table = (Table) tableMappings.next();
if ( table.isPhysicalTable() ) {
Label label = CypherCRUD.nodeLabel( table.getName() );
PrimaryKey primaryKey = table.getPrimaryKey();
createConstraint( neo4jDb, table, label, primaryKey );
@SuppressWarnings("unchecked")
Iterator<Column> columnIterator = table.getColumnIterator();
while ( columnIterator.hasNext() ) {
Column column = columnIterator.next();
if ( column.isUnique() ) {
createUniqueConstraintIfMissing( neo4jDb, label, column.getName() );
}
}
Iterator<UniqueKey> uniqueKeyIterator = table.getUniqueKeyIterator();
while ( uniqueKeyIterator.hasNext() ) {
createConstraint( neo4jDb, table, label, uniqueKeyIterator.next() );
}
}
}
}
private void createConstraint(GraphDatabaseService neo4jDb, Table table, Label label, Constraint constraint) {
if ( constraint != null ) {
if ( constraint.getColumnSpan() == 1 ) {
String propertyName = constraint.getColumn( 0 ).getName();
createUniqueConstraintIfMissing( neo4jDb, label, propertyName );
}
else if ( log.isEnabled( Level.WARN ) ) {
logMultipleColumnsWarning( table, constraint );
}
}
}
private void logMultipleColumnsWarning(Table table, Constraint constraint) {
StringBuilder builder = new StringBuilder();
for ( Iterator<Column> columnIterator = constraint.getColumnIterator(); columnIterator.hasNext(); ) {
Column column = columnIterator.next();
builder.append( ", " );
builder.append( column.getName() );
}
String columns = "[" + builder.substring( 2 ) + "]";
log.constraintSpanningMultipleColumns( constraint.getName(), table.getName(), columns );
}
private void createUniqueConstraintIfMissing(GraphDatabaseService neo4jDb, Label label, String property) {
if ( isMissingUniqueConstraint( neo4jDb, label, property ) ) {
log.tracef( "Creating unique constraint for nodes labeled as %1$s on property %2$s", label, property);
neo4jDb.schema().constraintFor( label ).assertPropertyIsUnique( property ).create();
}
else {
log.tracef( "Unique constraint already exists for nodes labeled as %1$s on property %2$s", label, property);
}
}
private boolean isMissingUniqueConstraint(GraphDatabaseService neo4jDb, Label label, String propertyName) {
Iterable<ConstraintDefinition> constraints = neo4jDb.schema().getConstraints( label );
for ( ConstraintDefinition constraint : constraints ) {
if ( constraint.isConstraintType( ConstraintType.UNIQUENESS ) ) {
for ( String propertyKey : constraint.getPropertyKeys() ) {
if ( propertyKey.equals( propertyName ) ) {
return false;
}
}
}
}
return true;
}
}
| OGM-547 Avoid the creation of unique constraints on foreign key columns
Neo4j does not create properties for foreign key columns, so we don't
need to create a constraint for them
| neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/impl/Neo4jSchemaDefiner.java | OGM-547 Avoid the creation of unique constraints on foreign key columns |
|
Java | apache-2.0 | fb2538f0d1532beefcbbf327825d2c864625c0bb | 0 | ymittal/codeu_project_2017,ymittal/codeu_project_2017 | package com.google.codeu.chatme.presenter;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.codeu.chatme.R;
import com.google.codeu.chatme.model.User;
import com.google.codeu.chatme.utility.FirebaseUtil;
import com.google.codeu.chatme.view.login.LoginActivity;
import com.google.codeu.chatme.view.tabs.ProfileFragment;
import com.google.codeu.chatme.view.tabs.ProfileView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
/**
* Following MVP design pattern, this class encapsulates the functionality to
* perform user profile changes and log out using Firebase
*
* @see LoginActivityInteractor for documentation on interface methods
*/
public class ProfilePresenter implements ProfileInteractor {
private static final String TAG = ProfilePresenter.class.getName();
private DatabaseReference mRootRef;
private final ProfileView view;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
/**
* Sets up the presenter with a reference to the {@link ProfileFragment}.
* Additionally, adds {@link com.google.firebase.auth.FirebaseAuth.AuthStateListener}
* to {@link FirebaseAuth} instance to detect changed in user authentication status
* Refer to {@link ProfilePresenter#postConstruct()}
*
* @param view a reference to {@link LoginActivity}
*/
public ProfilePresenter(final ProfileView view) {
this.view = view;
}
@javax.annotation.PostConstruct
public void postConstruct() {
this.mRootRef = FirebaseDatabase.getInstance().getReference();
this.mAuth = FirebaseAuth.getInstance();
this.mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
Log.d(TAG, "onAuthStateChanged:signed_out");
view.openLoginActivity();
}
}
};
}
/**
* Get current user's profile information and store in User object
*/
public void getUserProfile() {
mRootRef.child("users").child(FirebaseUtil.getCurrentUserUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
view.setUserProfile(user);
Log.i(TAG, "getUserProfile:success profile data loaded");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "getUserProfile:failure could not load profile data");
}
});
}
@SuppressWarnings("VisibleForTests")
@Override
public void uploadProfilePictureToStorage(final Uri data) {
view.showProgressDialog(R.string.progress_upload_pic);
StorageReference filepath = FirebaseStorage.getInstance().getReference()
.child("profile-pics").child(FirebaseUtil.getCurrentUserUid());
filepath.putFile(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadUrl = taskSnapshot.getDownloadUrl().toString();
Log.i(TAG, "updateProfilePicture:success:downloadUrl " + downloadUrl);
view.setProfilePicture(downloadUrl);
updateUserPhotoUrl(downloadUrl);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "updateProfilePicture:failure");
view.hideProgressDialog();
view.makeToast(e.getMessage());
}
});
}
/**
* Updates logged-in user's profile pic storage url
*
* @param downloadUri new profile pic download url
*/
private void updateUserPhotoUrl(String downloadUri) {
mRootRef.child("users").child(FirebaseUtil.getCurrentUserUid())
.child("photoUrl").setValue(downloadUri.toString());
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(Uri.parse(downloadUri))
.build();
FirebaseUtil.getCurrentUser().updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.i(TAG, "updateUserPhotoUrl:success");
} else {
Log.e(TAG, "updateUserPhotoUrl:failure");
}
}
});
}
/**
* Signs out current user
*/
public void signOut() {
mAuth.signOut();
}
/**
* Updates current user's profile based on provided parameters
*
* @param fullName user's full name
* @param username user's username
* @param password user's password
*/
public void updateUser(String fullName, String username, String password) {
updateFullName(fullName);
updateUserName(username);
updatePassword(password);
}
/**
* Updates logged-in user's full name
*
* @param fullName new full name
*/
private void updateFullName(final String fullName) {
if (fullName.isEmpty()) {
return;
}
view.showProgressDialog(R.string.progress_update_name);
mRootRef.child("users").child(FirebaseUtil.getCurrentUserUid())
.child("fullName").setValue(fullName);
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(fullName)
.build();
FirebaseUtil.getCurrentUser().updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
view.hideProgressDialog();
if (task.isSuccessful()) {
Log.d(TAG, "updateFullName:success " + fullName);
view.makeToast(R.string.toast_update_name);
} else {
Log.e(TAG, "updateFullName:failure");
view.makeToast(task.getException().getMessage());
}
}
});
}
/**
* Updates logged-in user's username
*
* @param username new username
*/
private void updateUserName(String username) {
if (username.isEmpty()) {
return;
}
mRootRef.child("users").child(FirebaseUtil.getCurrentUserUid())
.child("username").setValue(username);
Log.i(TAG, "updateUsername:success " + FirebaseUtil.getCurrentUserUid());
}
/**
* Updates logged-in user's password
*
* @param password new password
*/
public void updatePassword(String password) {
if (password.isEmpty()) {
return;
}
view.showProgressDialog(R.string.progress_update_pwd);
FirebaseUtil.getCurrentUser().updatePassword(password)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
view.hideProgressDialog();
if (task.isSuccessful()) {
Log.i(TAG, "updatePassword:success");
view.makeToast(R.string.toast_pwd_name);
} else {
Log.e(TAG, "updatePassword:failure");
view.makeToast(task.getException().getMessage());
}
}
});
}
/**
* Delete current user's account from firebase auth and database
*/
public void deleteAccount() {
mRootRef.child("users").child(FirebaseUtil.getCurrentUserUid())
.removeValue();
FirebaseUtil.getCurrentUser().delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.i(TAG, "deleteAccount:success account deleted");
view.openLoginActivity();
} else {
Log.e(TAG, "deleteAccount:failure account could not be deleted");
view.makeToast(task.getException().getMessage());
}
}
});
}
@Override
public void setAuthStateListener() {
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void removeAuthStateListener() {
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
| android/app/src/main/java/com/google/codeu/chatme/presenter/ProfilePresenter.java | package com.google.codeu.chatme.presenter;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.codeu.chatme.R;
import com.google.codeu.chatme.model.User;
import com.google.codeu.chatme.utility.FirebaseUtil;
import com.google.codeu.chatme.view.login.LoginActivity;
import com.google.codeu.chatme.view.tabs.ProfileFragment;
import com.google.codeu.chatme.view.tabs.ProfileView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
/**
* Following MVP design pattern, this class encapsulates the functionality to
* perform user profile changes and log out using Firebase
*
* @see LoginActivityInteractor for documentation on interface methods
*/
public class ProfilePresenter implements ProfileInteractor {
private static final String TAG = ProfilePresenter.class.getName();
private DatabaseReference mRootRef;
private final ProfileView view;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
/**
* Sets up the presenter with a reference to the {@link ProfileFragment}.
* Additionally, adds {@link com.google.firebase.auth.FirebaseAuth.AuthStateListener}
* to {@link FirebaseAuth} instance to detect changed in user authentication status
* Refer to {@link ProfilePresenter#postConstruct()}
*
* @param view a reference to {@link LoginActivity}
*/
public ProfilePresenter(final ProfileView view) {
this.view = view;
}
@javax.annotation.PostConstruct
public void postConstruct() {
this.mRootRef = FirebaseDatabase.getInstance().getReference();
this.mAuth = FirebaseAuth.getInstance();
this.mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
Log.d(TAG, "onAuthStateChanged:signed_out");
view.openLoginActivity();
}
}
};
}
/**
* Get current user's profile information and store in User object
*/
public void getUserProfile() {
DatabaseReference ref = mRootRef.child("users");
ref.child(FirebaseUtil.getCurrentUserUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
view.setUserProfile(user);
Log.i(TAG, "getUserProfile:success profile data loaded");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "getUserProfile:failure could not load profile data");
}
});
}
@SuppressWarnings("VisibleForTests")
@Override
public void uploadProfilePictureToStorage(final Uri data) {
view.showProgressDialog(R.string.progress_upload_pic);
StorageReference filepath = FirebaseStorage.getInstance().getReference()
.child("profile-pics").child(FirebaseUtil.getCurrentUserUid());
filepath.putFile(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadUrl = taskSnapshot.getDownloadUrl().toString();
Log.i(TAG, "updateProfilePicture:success:downloadUrl " + downloadUrl);
view.setProfilePicture(downloadUrl);
updateUserPhotoUrl(downloadUrl);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "updateProfilePicture:failure");
view.hideProgressDialog();
view.makeToast(e.getMessage());
}
});
}
/**
* Updates logged-in user's profile pic storage url
*
* @param downloadUri new profile pic download url
*/
private void updateUserPhotoUrl(String downloadUri) {
mRootRef.child("users").child(FirebaseUtil.getCurrentUserUid())
.child("photoUrl").setValue(downloadUri.toString());
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(Uri.parse(downloadUri))
.build();
FirebaseUtil.getCurrentUser().updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.i(TAG, "updateUserPhotoUrl:success");
} else {
Log.e(TAG, "updateUserPhotoUrl:failure");
}
}
});
}
/**
* Signs out current user
*/
public void signOut() {
mAuth.signOut();
}
/**
* Updates current user's profile based on provided parameters
*
* @param fullName user's full name
* @param username user's username
* @param password user's password
*/
public void updateUser(String fullName, String username, String password) {
updateFullName(fullName);
updateUserName(username);
updatePassword(password);
}
/**
* Updates logged-in user's full name
*
* @param fullName new full name
*/
private void updateFullName(final String fullName) {
if (fullName.isEmpty()) {
return;
}
view.showProgressDialog(R.string.progress_update_name);
mRootRef.child("users").child(FirebaseUtil.getCurrentUserUid())
.child("fullName").setValue(fullName);
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(fullName)
.build();
FirebaseUtil.getCurrentUser().updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
view.hideProgressDialog();
if (task.isSuccessful()) {
Log.d(TAG, "updateFullName:success " + fullName);
view.makeToast(R.string.toast_update_name);
} else {
Log.e(TAG, "updateFullName:failure");
view.makeToast(task.getException().getMessage());
}
}
});
}
/**
* Updates logged-in user's username
*
* @param username new username
*/
private void updateUserName(String username) {
if (username.isEmpty()) {
return;
}
mRootRef.child("users").child(FirebaseUtil.getCurrentUserUid())
.child("username").setValue(username);
Log.i(TAG, "updateUsername:success " + FirebaseUtil.getCurrentUserUid());
}
/**
* Updates logged-in user's password
*
* @param password new password
*/
public void updatePassword(String password) {
if (password.isEmpty()) {
return;
}
view.showProgressDialog(R.string.progress_update_pwd);
FirebaseUtil.getCurrentUser().updatePassword(password)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
view.hideProgressDialog();
if (task.isSuccessful()) {
Log.i(TAG, "updatePassword:success");
view.makeToast(R.string.toast_pwd_name);
} else {
Log.e(TAG, "updatePassword:failure");
view.makeToast(task.getException().getMessage());
}
}
});
}
/**
* Delete current user's account from firebase auth and database
*/
public void deleteAccount() {
mRootRef.child("users").child(FirebaseUtil.getCurrentUserUid())
.removeValue();
FirebaseUtil.getCurrentUser().delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.i(TAG, "deleteAccount:success account deleted");
view.openLoginActivity();
} else {
Log.e(TAG, "deleteAccount:failure account could not be deleted");
view.makeToast(task.getException().getMessage());
}
}
});
}
@Override
public void setAuthStateListener() {
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void removeAuthStateListener() {
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
| Reverted a few changes
| android/app/src/main/java/com/google/codeu/chatme/presenter/ProfilePresenter.java | Reverted a few changes |
|
Java | apache-2.0 | abb0c1901f1fe9b3c4723a8c9ac5dc6dc247e217 | 0 | f2prateek/android-couchpotato | /*
* Copyright 2014 Prateek Srivastava (@f2prateek)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.f2prateek.couchpotato.ui.views;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.f2prateek.couchpotato.Events;
import com.f2prateek.couchpotato.R;
import com.f2prateek.couchpotato.data.api.Movie;
import com.squareup.otto.Bus;
import com.squareup.picasso.Picasso;
public class MovieGridItem extends FrameLayout {
@InjectView(R.id.movie_poster) ImageView image;
@InjectView(R.id.movie_title) TextView title;
private Movie movie;
private Bus bus;
public MovieGridItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override protected void onFinishInflate() {
super.onFinishInflate();
ButterKnife.inject(this);
}
public void bindTo(Movie movie, Picasso picasso, Bus bus) {
this.movie = movie;
this.bus = bus;
picasso.load(movie.poster()).fit().centerCrop().into(image);
title.setText(movie.title());
}
@OnClick(R.id.movie_poster) public void onMovieClicked() {
int[] screenLocation = new int[2];
getLocationOnScreen(screenLocation);
int width = getWidth();
int height = getHeight();
bus.post(
new Events.OnMovieClickedEvent(movie, height, width, screenLocation[0], screenLocation[1]));
}
}
| couchpotato/src/main/java/com/f2prateek/couchpotato/ui/views/MovieGridItem.java | /*
* Copyright 2014 Prateek Srivastava (@f2prateek)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.f2prateek.couchpotato.ui.views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.f2prateek.couchpotato.Events;
import com.f2prateek.couchpotato.R;
import com.f2prateek.couchpotato.data.api.Movie;
import com.squareup.otto.Bus;
import com.squareup.picasso.Picasso;
public class MovieGridItem extends FrameLayout {
@InjectView(R.id.movie_poster) ImageView image;
@InjectView(R.id.movie_title) TextView title;
private Movie movie;
private Bus bus;
public MovieGridItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override protected void onFinishInflate() {
super.onFinishInflate();
ButterKnife.inject(this);
}
public void bindTo(Movie movie, Picasso picasso, Bus bus) {
this.movie = movie;
this.bus = bus;
picasso.load(movie.poster()).fit().centerCrop().into(image);
title.setText(movie.title());
}
@OnClick(R.id.movie_poster) public void onMovieClicked(View view) {
int[] screenLocation = new int[2];
view.getLocationOnScreen(screenLocation);
int width = view.getWidth();
int height = view.getHeight();
bus.post(
new Events.OnMovieClickedEvent(movie, height, width, screenLocation[0], screenLocation[1]));
}
}
| Get required fields directly from view.
| couchpotato/src/main/java/com/f2prateek/couchpotato/ui/views/MovieGridItem.java | Get required fields directly from view. |
|
Java | apache-2.0 | 4a8bad0b7089c917dcde9fa4f3095c9460142cef | 0 | jitsi/jitsi-videobridge,parlaylabs/jitsi-videobridge,jitsi/jitsi-videobridge,gpolitis/jitsi-videobridge,davidertel/jitsi-videobridge,gpolitis/jitsi-videobridge,gpolitis/jitsi-videobridge,jitsi/jitsi-videobridge,matteocampana/jitsi-videobridge,parlaylabs/jitsi-videobridge,jitsi/jitsi-videobridge,davidertel/jitsi-videobridge,parlaylabs/jitsi-videobridge,matteocampana/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge,matteocampana/jitsi-videobridge,davidertel/jitsi-videobridge,parlaylabs/jitsi-videobridge,jitsi/jitsi-videobridge | /*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.ratecontrol;
import net.java.sip.communicator.util.*;
import org.jitsi.impl.neomedia.rtp.remotebitrateestimator.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.rtp.*;
import org.jitsi.videobridge.*;
import org.jitsi.videobridge.simulcast.*;
import org.jitsi.videobridge.transform.*;
import java.util.*;
/**
* Monitors the available bandwidth and the sending bitrate to the owning
* endpoint, and if it detects that we are oversending, disables the highest
* simulcast layer.
*
* @author Boris Grozev
*/
public class AdaptiveSimulcastBitrateController
extends BitrateController
implements BandwidthEstimator.Listener,
RecurringProcessible
{
/**
* Whether the values for the constants have been initialized or not.
*/
private static boolean configurationInitialized = false;
/**
* The interval at which {@link #process()} should be called, in
* milliseconds.
*/
private static int PROCESS_INTERVAL_MS = 500;
/**
* The name of the property which controls the value of {@link
* #PROCESS_INTERVAL_MS}.
*/
private static final String PROCESS_INTERVAL_MS_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".PROCESS_INTERVAL_MS";
/**
* See {@link #CLIMB_MIN_RATIO}.
* This should probably be kept <OVERSENDING_INTERVAL, otherwise we will not
* detect the climb quickly enough after a drop in BWE and might trigger
* prematurely.
*/
private static int CLIMB_INTERVAL_MS = 4500;
/**
* The name of the property which controls the value of {@link
* #CLIMB_INTERVAL_MS}.
*/
private static final String CLIMB_INTERVAL_MS_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".CLIMB_INTERVAL_MS";
/**
* We consider that the bandwidth estimation is in a climb if the values
* have not been decreasing in the last {@link #CLIMB_INTERVAL_MS} and the
* max/min ratio is at least CLIMB_MIN_RATIO.
*/
private static double CLIMB_MIN_RATIO = 1.05;
/**
* The name of the property which controls the value of {@link
* #CLIMB_MIN_RATIO}.
*/
private static final String CLIMB_MIN_RATIO_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".CLIMB_MIN_RATIO";
/**
* We consider that we are oversending if we are sending at least
* OVERSENDING_COEF times the current bandwidth estimation.
*/
private static double OVERSENDING_COEF = 1.3;
/**
* The name of the property which controls the value of {@link
* #OVERSENDING_COEF}.
*/
private static final String OVERSENDING_COEF_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".OVERSENDING_COEF_PNAME";
/**
* The length in milliseconds of the interval during which we have to be
* oversending before we trigger.
*/
private static int OVERSENDING_INTERVAL_MS = 5000;
/**
* The name of the property which controls the value of {@link
* #OVERSENDING_INTERVAL_MS}.
*/
private static final String OVERSENDING_INTERVAL_MS_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".OVERSENDING_INTERVAL_MS_PNAME";
/**
* The length of the interval (in milliseconds) after the first data point
* during which triggering is disabled.
* Should probably be kept >CLIMB_INTERVAL_MS, since in the first
* CLIMB_INTERVAL_MS the climb detection may give false-negatives.
*/
private static int INITIAL_PERIOD_MS = 8000;
/**
* The name of the property which controls the value of {@link
* #INITIAL_PERIOD_MS}.
*/
private static final String INITIAL_PERIOD_MS_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".INITIAL_PERIOD_MS";
/**
* The "target order" of the high quality layer.
*/
private static final int TARGET_ORDER_HD = 2;
/**
* Whether or not to actually disable the HD layer if the right conditions
* occur. Keeping it off while adaptive-simulcast is enabled allows for data
* collection without disruptions.
*/
private static boolean ENABLE_TRIGGER = true;
/**
* The name of the property which controls the value of {@link
* #ENABLE_TRIGGER}.
*/
private static final String ENABLE_TRIGGER_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".ENABLE_TRIGGER";
/**
* The <tt>Logger</tt> used by the {@link
* AdaptiveSimulcastBitrateController} class and its instances to print
* debug information.
*/
private static final org.jitsi.util.Logger logger
= org.jitsi.util.Logger.getLogger(
AdaptiveSimulcastBitrateController.class);
/**
* The {@link RecurringProcessibleExecutor} which will periodically call
* {@link #process()} on active {@link AdaptiveSimulcastBitrateController}
* instances.
*/
private static RecurringProcessibleExecutor recurringProcessibleExecutor;
/**
* Initializes the constants used by this class from the configuration.
*/
private static void initializeConfiguration(ConfigurationService cfg)
{
synchronized (AdaptiveSimulcastBitrateController.class)
{
if (configurationInitialized)
return;
configurationInitialized = true;
if (cfg != null)
{
PROCESS_INTERVAL_MS
= cfg.getInt(PROCESS_INTERVAL_MS_PNAME, PROCESS_INTERVAL_MS);
CLIMB_INTERVAL_MS
= cfg.getInt(CLIMB_INTERVAL_MS_PNAME, CLIMB_INTERVAL_MS);
CLIMB_MIN_RATIO
= cfg.getDouble(CLIMB_MIN_RATIO_PNAME, CLIMB_MIN_RATIO);
OVERSENDING_COEF
= cfg.getDouble(OVERSENDING_COEF_PNAME, OVERSENDING_COEF);
OVERSENDING_INTERVAL_MS
= cfg.getInt(
OVERSENDING_INTERVAL_MS_PNAME, OVERSENDING_INTERVAL_MS);
INITIAL_PERIOD_MS
= cfg.getInt(INITIAL_PERIOD_MS_PNAME, INITIAL_PERIOD_MS);
ENABLE_TRIGGER
= cfg.getBoolean(ENABLE_TRIGGER_PNAME, ENABLE_TRIGGER);
}
recurringProcessibleExecutor = new RecurringProcessibleExecutor();
}
}
/**
* The {@link VideoChannel} which owns this {@link
* AdaptiveSimulcastBitrateController}.
*/
private final VideoChannel channel;
/**
* The latest estimation of the available bandwidth as reported by our
* {@link Channel}'s {@link MediaStream}'s {@link BandwidthEstimator}.
*/
private long latestBwe = -1;
/**
* The time that {@link #process()} was last called.
*/
private long lastUpdateTime = -1;
/**
* Whether this {@link AdaptiveSimulcastBitrateController} has triggered
* suppression of the HD layer.
*/
private boolean triggered = false;
/**
* A queue which holds recent data about the sending bitrate and available
* bandwidth.
*/
private History history = new History();
/**
* Initializes a new {@link AdaptiveSimulcastBitrateController} instance.
*
* @param channel the {@link VideoChannel} which owns this instance.
* serve.
*/
public AdaptiveSimulcastBitrateController(
LastNController lastNController,
VideoChannel channel)
{
this.channel = channel;
initializeConfiguration(
ServiceUtils.getService(
channel.getBundleContext(),
ConfigurationService.class));
// Create a bandwidth estimator and hook us up to changes to the
// estimation.
BandwidthEstimator be
= ((VideoMediaStream) channel.getStream())
.getOrCreateBandwidthEstimator();
be.addListener(this);
recurringProcessibleExecutor.registerRecurringProcessible(this);
}
/**
* Releases resources used by this instance and stops the periodic execution
* of {@link #process()}.
*/
@Override
public void close()
{
recurringProcessibleExecutor.deRegisterRecurringProcessible(this);
}
/**
* Notifies this instance that the estimation of the available bandwidth
* has changed.
*
* @param bwe the new estimation of the available bandwidth in bits per second.
*/
@Override
public void bandwidthEstimationChanged(long bwe)
{
latestBwe = bwe;
}
/**
* @return the current rate at which we are sending data to the remote
* endpoint.
*/
private long getSendingBitrate()
{
return channel.getStream().getMediaStreamStats().getSendingBitrate();
}
/**
* Enables or disables the sending of the highest quality simulcast layer
* (as defined by {@link #TARGET_ORDER_HD} to {@link #channel}.
* @param enable whether to enable or disable it.
*/
private void enableHQLayer(boolean enable)
{
SimulcastEngine simulcastEngine
= channel.getTransformEngine().getSimulcastEngine();
SimulcastSenderManager ssm
= simulcastEngine.getSimulcastSenderManager();
if (enable)
{
ssm.setOverrideOrder(
SimulcastSenderManager.SIMULCAST_LAYER_ORDER_NO_OVERRIDE);
logger.info("Enabling HQ layer for endpoint " + getEndpointID());
}
else
{
ssm.setOverrideOrder(TARGET_ORDER_HD - 1);
logger.info("Disabling HQ layer for endpoint " + getEndpointID());
}
}
/**
* {@inheritDoc}
* @return Zero.
*/
@Override
public long process()
{
long now = System.currentTimeMillis();
lastUpdateTime = now;
if (triggered)
{
// We may eventually want to return or even close() here. For the
// time being, we go on in order to collect data.
//return 0;
}
long bwe = latestBwe;
long sbr = getSendingBitrate();
if (bwe == -1 || sbr == -1)
{
return 0; //no data yet
}
history.add(bwe, sbr, now);
// In the "initial period".
boolean inInitial = (now - history.firstAdd < INITIAL_PERIOD_MS);
// The bandwidth estimation is currently increasing.
boolean climbing
= history.isBweClimbing(CLIMB_INTERVAL_MS, CLIMB_MIN_RATIO);
// We have been consistently (for over OVERSENDING_INTERVAL ms) sending
// too much.
boolean oversending = true;
long lastTimeNotOversending
= history.getLastTimeNotOversending(OVERSENDING_COEF);
if (lastTimeNotOversending != -1
&& now - lastTimeNotOversending < OVERSENDING_INTERVAL_MS)
{
oversending = false;
}
// There is a sender with target order == hq && isStreaming().
boolean hqLayerAvailable = isHqLayerAvailable();
boolean trigger
= oversending && !climbing && hqLayerAvailable && !inInitial;
if (logger.isTraceEnabled())
{
// Temporary logs to facilitate analysis
String c = climbing ? " 9000000" : " 9500000";
String o = oversending ? " 10000000" : " 10500000";
String h = hqLayerAvailable ? " 11000000" : " 11500000";
String t = trigger ? " 1" : " -1";
logger.trace("Endpoint " + getEndpointID() + " " + sbr + " "
+ bwe + c + o + h + t);
}
if (trigger && ENABLE_TRIGGER)
{
enableHQLayer(false);
}
return 0;
}
/**
* Returns true if and only if our {@link VideoChannel} has a
* {@link SimulcastSender} with "target order" at least
* {@link #TARGET_ORDER_HD} (i.e. a "selected endpoint"), and such that its
* corresponding {@link SimulcastReceiver} is currently receiving the
* stream with the highest "target order".
*
* That is, checks if we are currently sending at least one high quality
* layer to the remote endpoint.
*
* TODO: we may want to take lastN/forwardedEndpoints into account.
*/
private boolean isHqLayerAvailable()
{
RtpChannelTransformEngine rtpChannelTransformEngine
= channel.getTransformEngine();
if (rtpChannelTransformEngine == null)
{
logger.warn("rtpChannelTransformEngine is null");
return false;
}
SimulcastEngine simulcastEngine
= rtpChannelTransformEngine.getSimulcastEngine();
if (simulcastEngine == null)
{
logger.warn("simulcastEngine is null");
return false;
}
SimulcastSenderManager ssm
= simulcastEngine.getSimulcastSenderManager();
if (ssm == null)
{
logger.warn("ssm is null");
return false;
}
Map<SimulcastReceiver, SimulcastSender> senders = ssm.getSenders();
if (senders == null)
{
logger.warn("senders is null");
return false;
}
for (Map.Entry<SimulcastReceiver, SimulcastSender> entry
: senders.entrySet())
{
try
{
if (entry.getValue().getTargetOrder() >= TARGET_ORDER_HD)
{
SimulcastStream ss
= entry.
getKey().
getSimulcastStream(
entry.getValue().getTargetOrder());
if (ss.isStreaming())
{
return true;
}
}
}
catch (Throwable t)
{
logger.warn("Checking for HQ layer failed for an endpoint.", t);
}
}
return false;
}
@Override
public long getTimeUntilNextProcess()
{
return
(lastUpdateTime < 0L)
? 0L
: lastUpdateTime + PROCESS_INTERVAL_MS
- System.currentTimeMillis();
}
/**
* @return the ID of {@link #channel}'s endpoint.
*/
private String getEndpointID()
{
Endpoint endpoint = channel.getEndpoint();
return endpoint == null ? "null" : endpoint.getID();
}
private static class History
{
int LENGTH_MS = Math.max(CLIMB_INTERVAL_MS, OVERSENDING_INTERVAL_MS);
int LENGTH = 1 + LENGTH_MS / PROCESS_INTERVAL_MS;
long[] bwe = new long[LENGTH];
long[] sbr = new long[LENGTH];
long[] ts = new long[LENGTH];
int head = 0;
int size = 0;
long firstAdd = -1;
private void add(long currentBwe, long currentSbr, long now)
{
if (firstAdd == -1)
firstAdd = now;
head = (head + 1) % LENGTH;
size += 1;
if (size > bwe.length)
size -= 1;
bwe[head] = currentBwe;
sbr[head] = currentSbr;
ts[head] = now;
}
private boolean isBweClimbing(int ms, double minRatio)
{
if (size <= 1)
return true;
long min = bwe[head];
long now = System.currentTimeMillis();
for (int i = 0; i < size - 1; i++)
{
int curIdx = (head - i + LENGTH) % LENGTH;
int prevIdx = (curIdx - 1 + LENGTH) % LENGTH;
if (ts[prevIdx] + ms < now)
break;
if (bwe[prevIdx] < min)
min = bwe[prevIdx];
// not monotonically increasing
if (bwe[prevIdx] >= bwe[curIdx])
return false;
}
return ((double) bwe[head]) / min > minRatio;
}
//get the last time in ms that sbr < ratio * bwe
//sbr
private long getLastTimeNotOversending(double ratio)
{
for (int i = 0; i < size; i++)
{
int idx = (head - i + LENGTH) % LENGTH;
if (sbr[idx] <= bwe[idx] * ratio)
{
return ts[idx];
}
}
return -1;
}
}
}
| src/main/java/org/jitsi/videobridge/ratecontrol/AdaptiveSimulcastBitrateController.java | /*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.ratecontrol;
import net.java.sip.communicator.util.*;
import org.jitsi.impl.neomedia.rtp.remotebitrateestimator.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.rtp.*;
import org.jitsi.videobridge.*;
import org.jitsi.videobridge.simulcast.*;
import org.jitsi.videobridge.transform.*;
import java.util.*;
/**
* Monitors the available bandwidth and the sending bitrate to the owning
* endpoint, and if it detects that we are oversending, disables the highest
* simulcast layer.
*
* @author Boris Grozev
*/
public class AdaptiveSimulcastBitrateController
extends BitrateController
implements BandwidthEstimator.Listener,
RecurringProcessible
{
/**
* Whether the values for the constants have been initialized or not.
*/
private static boolean configurationInitialized = false;
/**
* The interval at which {@link #process()} should be called, in
* milliseconds.
*/
private static int PROCESS_INTERVAL_MS = 500;
/**
* The name of the property which controls the value of {@link
* #PROCESS_INTERVAL_MS}.
*/
private static final String PROCESS_INTERVAL_MS_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".PROCESS_INTERVAL_MS";
/**
* See {@link #CLIMB_MIN_RATIO}.
* This should probably be kept <OVERSENDING_INTERVAL, otherwise we will not
* detect the climb quickly enough after a drop in BWE and might trigger
* prematurely.
*/
private static int CLIMB_INTERVAL_MS = 4500;
/**
* The name of the property which controls the value of {@link
* #CLIMB_INTERVAL_MS}.
*/
private static final String CLIMB_INTERVAL_MS_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".CLIMB_INTERVAL_MS";
/**
* We consider that the bandwidth estimation is in a climb if the values
* have not been decreasing in the last {@link #CLIMB_INTERVAL_MS} and the
* max/min ratio is at least CLIMB_MIN_RATIO.
*/
private static double CLIMB_MIN_RATIO = 1.05;
/**
* The name of the property which controls the value of {@link
* #CLIMB_MIN_RATIO}.
*/
private static final String CLIMB_MIN_RATIO_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".CLIMB_MIN_RATIO";
/**
* We consider that we are oversending if we are sending at least
* OVERSENDING_COEF times the current bandwidth estimation.
*/
private static double OVERSENDING_COEF = 1.3;
/**
* The name of the property which controls the value of {@link
* #OVERSENDING_COEF}.
*/
private static final String OVERSENDING_COEF_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".OVERSENDING_COEF_PNAME";
/**
* The length in milliseconds of the interval during which we have to be
* oversending before we trigger.
*/
private static int OVERSENDING_INTERVAL_MS = 5000;
/**
* The name of the property which controls the value of {@link
* #OVERSENDING_INTERVAL_MS}.
*/
private static final String OVERSENDING_INTERVAL_MS_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".OVERSENDING_INTERVAL_MS_PNAME";
/**
* The length of the interval (in milliseconds) after the first data point
* during which triggering is disabled.
* Should probably be kept >CLIMB_INTERVAL_MS, since in the first
* CLIMB_INTERVAL_MS the climb detection may give false-negatives.
*/
private static int INITIAL_PERIOD_MS = 8000;
/**
* The name of the property which controls the value of {@link
* #INITIAL_PERIOD_MS}.
*/
private static final String INITIAL_PERIOD_MS_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".INITIAL_PERIOD_MS";
/**
* The "target order" of the high quality layer.
*/
private static final int TARGET_ORDER_HD = 2;
/**
* Whether or not to actually disable the HD layer if the right conditions
* occur. Keeping it off while adaptive-simulcast is enabled allows for data
* collection without disruptions.
*/
private static boolean ENABLE_TRIGGER = true;
/**
* The name of the property which controls the value of {@link
* #ENABLE_TRIGGER}.
*/
private static final String ENABLE_TRIGGER_PNAME
= AdaptiveSimulcastBitrateController.class.getName()
+ ".ENABLE_TRIGGER";
/**
* The <tt>Logger</tt> used by the {@link
* AdaptiveSimulcastBitrateController} class and its instances to print
* debug information.
*/
private static final org.jitsi.util.Logger logger
= org.jitsi.util.Logger.getLogger(
AdaptiveSimulcastBitrateController.class);
/**
* The {@link RecurringProcessibleExecutor} which will periodically call
* {@link #process()} on active {@link AdaptiveSimulcastBitrateController}
* instances.
*/
private static RecurringProcessibleExecutor recurringProcessibleExecutor;
/**
* Initializes the constants used by this class from the configuration.
*/
private static void initializeConfiguration(ConfigurationService cfg)
{
if (configurationInitialized)
return;
synchronized (AdaptiveSimulcastBitrateController.class)
{
if (cfg != null)
{
PROCESS_INTERVAL_MS
= cfg.getInt(PROCESS_INTERVAL_MS_PNAME, PROCESS_INTERVAL_MS);
CLIMB_INTERVAL_MS
= cfg.getInt(CLIMB_INTERVAL_MS_PNAME, CLIMB_INTERVAL_MS);
CLIMB_MIN_RATIO
= cfg.getDouble(CLIMB_MIN_RATIO_PNAME, CLIMB_MIN_RATIO);
OVERSENDING_COEF
= cfg.getDouble(OVERSENDING_COEF_PNAME, OVERSENDING_COEF);
OVERSENDING_INTERVAL_MS
= cfg.getInt(
OVERSENDING_INTERVAL_MS_PNAME, OVERSENDING_INTERVAL_MS);
INITIAL_PERIOD_MS
= cfg.getInt(INITIAL_PERIOD_MS_PNAME, INITIAL_PERIOD_MS);
ENABLE_TRIGGER
= cfg.getBoolean(ENABLE_TRIGGER_PNAME, ENABLE_TRIGGER);
}
recurringProcessibleExecutor = new RecurringProcessibleExecutor();
configurationInitialized = true;
}
}
/**
* The {@link VideoChannel} which owns this {@link
* AdaptiveSimulcastBitrateController}.
*/
private final VideoChannel channel;
/**
* The latest estimation of the available bandwidth as reported by our
* {@link Channel}'s {@link MediaStream}'s {@link BandwidthEstimator}.
*/
private long latestBwe = -1;
/**
* The time that {@link #process()} was last called.
*/
private long lastUpdateTime = -1;
/**
* Whether this {@link AdaptiveSimulcastBitrateController} has triggered
* suppression of the HD layer.
*/
private boolean triggered = false;
/**
* A queue which holds recent data about the sending bitrate and available
* bandwidth.
*/
private History history = new History();
/**
* Initializes a new {@link AdaptiveSimulcastBitrateController} instance.
*
* @param channel the {@link VideoChannel} which owns this instance.
* serve.
*/
public AdaptiveSimulcastBitrateController(
LastNController lastNController,
VideoChannel channel)
{
this.channel = channel;
initializeConfiguration(
ServiceUtils.getService(
channel.getBundleContext(),
ConfigurationService.class));
// Create a bandwidth estimator and hook us up to changes to the
// estimation.
BandwidthEstimator be
= ((VideoMediaStream) channel.getStream())
.getOrCreateBandwidthEstimator();
be.addListener(this);
recurringProcessibleExecutor.registerRecurringProcessible(this);
}
/**
* Releases resources used by this instance and stops the periodic execution
* of {@link #process()}.
*/
@Override
public void close()
{
recurringProcessibleExecutor.deRegisterRecurringProcessible(this);
}
/**
* Notifies this instance that the estimation of the available bandwidth
* has changed.
*
* @param bwe the new estimation of the available bandwidth in bits per second.
*/
@Override
public void bandwidthEstimationChanged(long bwe)
{
latestBwe = bwe;
}
/**
* @return the current rate at which we are sending data to the remote
* endpoint.
*/
private long getSendingBitrate()
{
return channel.getStream().getMediaStreamStats().getSendingBitrate();
}
/**
* Enables or disables the sending of the highest quality simulcast layer
* (as defined by {@link #TARGET_ORDER_HD} to {@link #channel}.
* @param enable whether to enable or disable it.
*/
private void enableHQLayer(boolean enable)
{
SimulcastEngine simulcastEngine
= channel.getTransformEngine().getSimulcastEngine();
SimulcastSenderManager ssm
= simulcastEngine.getSimulcastSenderManager();
if (enable)
{
ssm.setOverrideOrder(
SimulcastSenderManager.SIMULCAST_LAYER_ORDER_NO_OVERRIDE);
logger.info("Enabling HQ layer for endpoint " + getEndpointID());
}
else
{
ssm.setOverrideOrder(TARGET_ORDER_HD - 1);
logger.info("Disabling HQ layer for endpoint " + getEndpointID());
}
}
/**
* {@inheritDoc}
* @return Zero.
*/
@Override
public long process()
{
long now = System.currentTimeMillis();
lastUpdateTime = now;
if (triggered)
{
// We may eventually want to return or even close() here. For the
// time being, we go on in order to collect data.
//return 0;
}
long bwe = latestBwe;
long sbr = getSendingBitrate();
if (bwe == -1 || sbr == -1)
{
return 0; //no data yet
}
history.add(bwe, sbr, now);
// In the "initial period".
boolean inInitial = (now - history.firstAdd < INITIAL_PERIOD_MS);
// The bandwidth estimation is currently increasing.
boolean climbing
= history.isBweClimbing(CLIMB_INTERVAL_MS, CLIMB_MIN_RATIO);
// We have been consistently (for over OVERSENDING_INTERVAL ms) sending
// too much.
boolean oversending = true;
long lastTimeNotOversending
= history.getLastTimeNotOversending(OVERSENDING_COEF);
if (lastTimeNotOversending != -1
&& now - lastTimeNotOversending < OVERSENDING_INTERVAL_MS)
{
oversending = false;
}
// There is a sender with target order == hq && isStreaming().
boolean hqLayerAvailable = isHqLayerAvailable();
boolean trigger
= oversending && !climbing && hqLayerAvailable && !inInitial;
if (logger.isTraceEnabled())
{
// Temporary logs to facilitate analysis
String c = climbing ? " 9000000" : " 9500000";
String o = oversending ? " 10000000" : " 10500000";
String h = hqLayerAvailable ? " 11000000" : " 11500000";
String t = trigger ? " 1" : " -1";
logger.trace("Endpoint " + getEndpointID() + " " + sbr + " "
+ bwe + c + o + h + t);
}
if (trigger && ENABLE_TRIGGER)
{
enableHQLayer(false);
}
return 0;
}
/**
* Returns true if and only if our {@link VideoChannel} has a
* {@link SimulcastSender} with "target order" at least
* {@link #TARGET_ORDER_HD} (i.e. a "selected endpoint"), and such that its
* corresponding {@link SimulcastReceiver} is currently receiving the
* stream with the highest "target order".
*
* That is, checks if we are currently sending at least one high quality
* layer to the remote endpoint.
*
* TODO: we may want to take lastN/forwardedEndpoints into account.
*/
private boolean isHqLayerAvailable()
{
RtpChannelTransformEngine rtpChannelTransformEngine
= channel.getTransformEngine();
if (rtpChannelTransformEngine == null)
{
logger.warn("rtpChannelTransformEngine is null");
return false;
}
SimulcastEngine simulcastEngine
= rtpChannelTransformEngine.getSimulcastEngine();
if (simulcastEngine == null)
{
logger.warn("simulcastEngine is null");
return false;
}
SimulcastSenderManager ssm
= simulcastEngine.getSimulcastSenderManager();
if (ssm == null)
{
logger.warn("ssm is null");
return false;
}
Map<SimulcastReceiver, SimulcastSender> senders = ssm.getSenders();
if (senders == null)
{
logger.warn("senders is null");
return false;
}
for (Map.Entry<SimulcastReceiver, SimulcastSender> entry
: senders.entrySet())
{
try
{
if (entry.getValue().getTargetOrder() >= TARGET_ORDER_HD)
{
SimulcastStream ss
= entry.
getKey().
getSimulcastStream(
entry.getValue().getTargetOrder());
if (ss.isStreaming())
{
return true;
}
}
}
catch (Throwable t)
{
logger.warn("Checking for HQ layer failed for an endpoint.", t);
}
}
return false;
}
@Override
public long getTimeUntilNextProcess()
{
return
(lastUpdateTime < 0L)
? 0L
: lastUpdateTime + PROCESS_INTERVAL_MS
- System.currentTimeMillis();
}
/**
* @return the ID of {@link #channel}'s endpoint.
*/
private String getEndpointID()
{
Endpoint endpoint = channel.getEndpoint();
return endpoint == null ? "null" : endpoint.getID();
}
private static class History
{
int LENGTH_MS = Math.max(CLIMB_INTERVAL_MS, OVERSENDING_INTERVAL_MS);
int LENGTH = 1 + LENGTH_MS / PROCESS_INTERVAL_MS;
long[] bwe = new long[LENGTH];
long[] sbr = new long[LENGTH];
long[] ts = new long[LENGTH];
int head = 0;
int size = 0;
long firstAdd = -1;
private void add(long currentBwe, long currentSbr, long now)
{
if (firstAdd == -1)
firstAdd = now;
head = (head + 1) % LENGTH;
size += 1;
if (size > bwe.length)
size -= 1;
bwe[head] = currentBwe;
sbr[head] = currentSbr;
ts[head] = now;
}
private boolean isBweClimbing(int ms, double minRatio)
{
if (size <= 1)
return true;
long min = bwe[head];
long now = System.currentTimeMillis();
for (int i = 0; i < size - 1; i++)
{
int curIdx = (head - i + LENGTH) % LENGTH;
int prevIdx = (curIdx - 1 + LENGTH) % LENGTH;
if (ts[prevIdx] + ms < now)
break;
if (bwe[prevIdx] < min)
min = bwe[prevIdx];
// not monotonically increasing
if (bwe[prevIdx] >= bwe[curIdx])
return false;
}
return ((double) bwe[head]) / min > minRatio;
}
//get the last time in ms that sbr < ratio * bwe
//sbr
private long getLastTimeNotOversending(double ratio)
{
for (int i = 0; i < size; i++)
{
int idx = (head - i + LENGTH) % LENGTH;
if (sbr[idx] <= bwe[idx] * ratio)
{
return ts[idx];
}
}
return -1;
}
}
}
| Fixes a syncronization issue reported by @gpolitis.
| src/main/java/org/jitsi/videobridge/ratecontrol/AdaptiveSimulcastBitrateController.java | Fixes a syncronization issue reported by @gpolitis. |
|
Java | apache-2.0 | e7fe1b24751de95ca4b08d75635e592539f05f77 | 0 | blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.buildinit.plugins.internal;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import org.apache.commons.lang.StringUtils;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.file.Directory;
import org.gradle.api.internal.DocumentationRegistry;
import org.gradle.buildinit.plugins.internal.modifiers.BuildInitDsl;
import org.gradle.buildinit.plugins.internal.modifiers.InsecureProtocolOption;
import org.gradle.internal.Cast;
import org.gradle.internal.UncheckedException;
import org.gradle.util.internal.GFileUtils;
import org.gradle.util.internal.GUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Assembles the parts of a build script.
*/
@SuppressWarnings("UnusedReturnValue")
public class BuildScriptBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(BuildScriptBuilder.class);
private final BuildInitDsl dsl;
private final String fileNameWithoutExtension;
private boolean externalComments;
private final MavenRepositoryURLHandler mavenRepoURLHandler;
private final List<String> headerLines = new ArrayList<>();
private final TopLevelBlock block;
public static BuildScriptBuilder forNewProjects(BuildInitDsl dsl, DocumentationRegistry documentationRegistry, String fileNameWithoutExtension) {
return new BuildScriptBuilder(dsl, documentationRegistry, fileNameWithoutExtension, InsecureProtocolOption.FAIL);
}
public static BuildScriptBuilder forMavenConversion(BuildInitDsl dsl, DocumentationRegistry documentationRegistry, String fileNameWithoutExtension, InsecureProtocolOption insecureProtocolHandler) {
return new BuildScriptBuilder(dsl, documentationRegistry, fileNameWithoutExtension, insecureProtocolHandler);
}
private BuildScriptBuilder(BuildInitDsl dsl, DocumentationRegistry documentationRegistry, String fileNameWithoutExtension, InsecureProtocolOption insecureProtocolHandler) {
this.dsl = dsl;
this.fileNameWithoutExtension = fileNameWithoutExtension;
this.mavenRepoURLHandler = MavenRepositoryURLHandler.forInsecureProtocolOption(insecureProtocolHandler, dsl, documentationRegistry);
block = new TopLevelBlock(this);
}
public BuildScriptBuilder withExternalComments() {
this.externalComments = true;
return this;
}
public String getFileNameWithoutExtension() {
return fileNameWithoutExtension;
}
/**
* Adds a comment to the header of the file.
*/
public BuildScriptBuilder fileComment(String comment) {
headerLines.addAll(splitComment(comment));
return this;
}
private static List<String> splitComment(String comment) {
return Splitter.on("\n").splitToList(comment.trim());
}
private static URI uriFromString(String uriAsString) {
try {
return new URI(uriAsString);
} catch (URISyntaxException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
/**
* Adds a plugin to be applied
*
* @param comment A description of why the plugin is required
*/
public BuildScriptBuilder plugin(@Nullable String comment, String pluginId) {
block.plugins.add(new PluginSpec(pluginId, null, comment));
return this;
}
/**
* Adds the plugin and config needed to support writing pre-compiled script plugins in the selected DSL in this project.
*/
public BuildScriptBuilder conventionPluginSupport(@Nullable String comment) {
Syntax syntax = syntaxFor(dsl);
block.repositories.gradlePluginPortal("Use the plugin portal to apply community plugins in convention plugins.");
syntax.configureConventionPlugin(comment, block.plugins, block.repositories);
return this;
}
/**
* Adds a plugin to be applied
*
* @param comment A description of why the plugin is required
*/
public BuildScriptBuilder plugin(@Nullable String comment, String pluginId, String version) {
block.plugins.add(new PluginSpec(pluginId, version, comment));
return this;
}
/**
* Adds one or more external dependencies to the specified configuration.
*
* @param configuration The configuration where the dependency should be added
* @param comment A description of why the dependencies are required
* @param dependencies the dependencies, in string notation
*/
public BuildScriptBuilder dependency(String configuration, @Nullable String comment, String... dependencies) {
dependencies().dependency(configuration, comment, dependencies);
return this;
}
/**
* Adds one or more external implementation dependencies.
*
* @param comment A description of why the dependencies are required
* @param dependencies The dependencies, in string notation
*/
public BuildScriptBuilder implementationDependency(@Nullable String comment, String... dependencies) {
return dependency("implementation", comment, dependencies);
}
/**
* Adds one or more dependency constraints to the implementation scope.
*
* @param comment A description of why the constraints are required
* @param dependencies The constraints, in string notation
*/
public BuildScriptBuilder implementationDependencyConstraint(@Nullable String comment, String... dependencies) {
dependencies().dependencyConstraint("implementation", comment, dependencies);
return this;
}
/**
* Adds one or more external test implementation dependencies.
*
* @param comment A description of why the dependencies are required
* @param dependencies The dependencies, in string notation
*/
public BuildScriptBuilder testImplementationDependency(@Nullable String comment, String... dependencies) {
return dependency("testImplementation", comment, dependencies);
}
/**
* Adds one or more external test runtime only dependencies.
*
* @param comment A description of why the dependencies are required
* @param dependencies The dependencies, in string notation
*/
public BuildScriptBuilder testRuntimeOnlyDependency(@Nullable String comment, String... dependencies) {
return dependency("testRuntimeOnly", comment, dependencies);
}
/**
* Creates a method invocation expression, to use as a method argument or the RHS of a property assignment.
*/
public Expression methodInvocationExpression(String methodName, Object... methodArgs) {
return new MethodInvocationExpression(null, methodName, expressionValues(methodArgs));
}
/**
* Creates a property expression, to use as a method argument or the RHS of a property assignment.
*/
public Expression propertyExpression(String value) {
return new LiteralValue(value);
}
/**
* Creates a property expression, to use as a method argument or the RHS of a property assignment.
*/
public Expression propertyExpression(Expression expression, String value) {
return new ChainedPropertyExpression((ExpressionValue) expression, new LiteralValue(value));
}
/**
* Creates an expression that references an element in a container.
*/
public Expression containerElementExpression(String container, String element) {
return new ContainerElementExpression(container, element);
}
private static List<ExpressionValue> expressionValues(Object... expressions) {
List<ExpressionValue> result = new ArrayList<>(expressions.length);
for (Object expression : expressions) {
result.add(expressionValue(expression));
}
return result;
}
private static Map<String, ExpressionValue> expressionMap(Map<String, ?> expressions) {
LinkedHashMap<String, ExpressionValue> result = new LinkedHashMap<>();
for (Map.Entry<String, ?> entry : expressions.entrySet()) {
result.put(entry.getKey(), expressionValue(entry.getValue()));
}
return result;
}
private static ExpressionValue expressionValue(Object expression) {
if (expression instanceof CharSequence) {
return new StringValue((CharSequence) expression);
}
if (expression instanceof ExpressionValue) {
return (ExpressionValue) expression;
}
if (expression instanceof Number || expression instanceof Boolean) {
return new LiteralValue(expression);
}
if (expression instanceof Map) {
return new MapLiteralValue(expressionMap(Cast.uncheckedNonnullCast(expression)));
}
if (expression instanceof Enum) {
return new EnumValue(expression);
}
throw new IllegalArgumentException("Don't know how to treat " + expression + " as an expression.");
}
/**
* Allows repositories to be added to this script.
*/
public RepositoriesBuilder repositories() {
return block.repositories;
}
/**
* Allows dependencies to be added to this script.
*/
public DependenciesBuilder dependencies() {
return block.dependencies;
}
/**
* Adds a top level method invocation statement.
*
* @return this
*/
public BuildScriptBuilder methodInvocation(@Nullable String comment, String methodName, Object... methodArgs) {
block.methodInvocation(comment, methodName, methodArgs);
return this;
}
/**
* Adds a top level method invocation statement.
*
* @return this
*/
public BuildScriptBuilder methodInvocation(@Nullable String comment, Expression target, String methodName, Object... methodArgs) {
block.methodInvocation(comment, target, methodName, methodArgs);
return this;
}
/**
* Adds a top level property assignment statement.
*
* @return this
*/
public BuildScriptBuilder propertyAssignment(@Nullable String comment, String propertyName, Object propertyValue) {
block.propertyAssignment(comment, propertyName, propertyValue, true);
return this;
}
/**
* Adds a top level block statement.
*
* @return The body of the block, to which further statements can be added.
*/
public ScriptBlockBuilder block(@Nullable String comment, String methodName) {
return block.block(comment, methodName);
}
/**
* Adds a top level block statement.
*/
public BuildScriptBuilder block(@Nullable String comment, String methodName, Action<? super ScriptBlockBuilder> blockContentBuilder) {
blockContentBuilder.execute(block.block(comment, methodName));
return this;
}
/**
* Adds a method invocation statement to the configuration of a particular task.
*/
public BuildScriptBuilder taskMethodInvocation(@Nullable String comment, String taskName, String taskType, String methodName, Object... methodArgs) {
block.tasks.add(
new TaskSelector(taskName, taskType),
new MethodInvocation(comment, new MethodInvocationExpression(null, methodName, expressionValues(methodArgs))));
return this;
}
/**
* Adds a property assignment statement to the configuration of a particular task.
*/
public BuildScriptBuilder taskPropertyAssignment(@Nullable String comment, String taskName, String taskType, String propertyName, Object propertyValue) {
block.tasks.add(
new TaskSelector(taskName, taskType),
new PropertyAssignment(comment, propertyName, expressionValue(propertyValue), true));
return this;
}
/**
* Adds a property assignment statement to the configuration of all tasks of a particular type.
*/
public BuildScriptBuilder taskPropertyAssignment(@Nullable String comment, String taskType, String propertyName, Object propertyValue) {
block.taskTypes.add(
new TaskTypeSelector(taskType),
new PropertyAssignment(comment, propertyName, expressionValue(propertyValue), true));
return this;
}
/**
* Registers a task.
*
* @return An expression that can be used to refer to the task later.
*/
public Expression taskRegistration(@Nullable String comment, String taskName, String taskType, Action<? super ScriptBlockBuilder> blockContentsBuilder) {
TaskRegistration registration = new TaskRegistration(comment, taskName, taskType);
block.add(registration);
blockContentsBuilder.execute(registration.body);
return registration;
}
/**
* Creates an element in the given container.
*
* @param varName A variable to use to reference the element, if required by the DSL. If {@code null}, then use the element name.
*
* @return An expression that can be used to refer to the element later in the script.
*/
public Expression createContainerElement(@Nullable String comment, String container, String elementName, @Nullable String varName) {
ContainerElement containerElement = new ContainerElement(comment, container, elementName, null, varName);
block.add(containerElement);
return containerElement;
}
public TemplateOperation create(Directory targetDirectory) {
return () -> {
File target = getTargetFile(targetDirectory);
GFileUtils.mkdirs(target.getParentFile());
try (PrintWriter writer = new PrintWriter(new FileWriter(target))) {
PrettyPrinter printer = new PrettyPrinter(syntaxFor(dsl), writer, externalComments);
printer.printFileHeader(headerLines);
block.writeBodyTo(printer);
} catch (Exception e) {
throw new GradleException("Could not generate file " + target + ".", e);
}
};
}
public List<String> extractComments() {
return block.extractComments();
}
private File getTargetFile(Directory targetDirectory) {
return targetDirectory.file(dsl.fileNameFor(fileNameWithoutExtension)).getAsFile();
}
private static Syntax syntaxFor(BuildInitDsl dsl) {
switch (dsl) {
case KOTLIN:
return new KotlinSyntax();
case GROOVY:
return new GroovySyntax();
default:
throw new IllegalStateException();
}
}
public interface Expression {
}
private interface ExpressionValue extends Expression {
boolean isBooleanType();
String with(Syntax syntax);
}
private static class ChainedPropertyExpression implements Expression, ExpressionValue {
private final ExpressionValue left;
private final ExpressionValue right;
public ChainedPropertyExpression(ExpressionValue left, ExpressionValue right) {
this.left = left;
this.right = right;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return left.with(syntax) + "." + right.with(syntax);
}
}
private static class StringValue implements ExpressionValue {
final CharSequence value;
StringValue(CharSequence value) {
this.value = value;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return syntax.string(value.toString());
}
}
private static class LiteralValue implements ExpressionValue {
final Object literal;
LiteralValue(Object literal) {
this.literal = literal;
}
@Override
public boolean isBooleanType() {
return literal instanceof Boolean;
}
@Override
public String with(Syntax syntax) {
return literal.toString();
}
}
private static class EnumValue implements ExpressionValue {
final Enum<?> literal;
EnumValue(Object literal) {
this.literal = Cast.uncheckedNonnullCast(literal);
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return literal.getClass().getSimpleName() + "." + literal.name();
}
}
private static class MapLiteralValue implements ExpressionValue {
final Map<String, ExpressionValue> literal;
public MapLiteralValue(Map<String, ExpressionValue> literal) {
this.literal = literal;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return syntax.mapLiteral(literal);
}
}
private static class MethodInvocationExpression implements ExpressionValue {
@Nullable
private final ExpressionValue target;
final String methodName;
final List<ExpressionValue> arguments;
MethodInvocationExpression(@Nullable ExpressionValue target, String methodName, List<ExpressionValue> arguments) {
this.target = target;
this.methodName = methodName;
this.arguments = arguments;
}
MethodInvocationExpression(String methodName) {
this(null, methodName, Collections.emptyList());
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
StringBuilder result = new StringBuilder();
if (target != null) {
result.append(target.with(syntax));
result.append('.');
}
result.append(methodName);
result.append("(");
for (int i = 0; i < arguments.size(); i++) {
ExpressionValue argument = arguments.get(i);
if (i == 0) {
result.append(syntax.firstArg(argument));
} else {
result.append(", ");
result.append(argument.with(syntax));
}
}
result.append(")");
return result.toString();
}
}
private static class ContainerElementExpression implements ExpressionValue {
private final String container;
private final String element;
public ContainerElementExpression(String container, String element) {
this.container = container;
this.element = element;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return syntax.containerElement(container, element);
}
}
private static class PluginSpec extends AbstractStatement {
final String id;
@Nullable
final String version;
PluginSpec(String id, @Nullable String version, String comment) {
super(comment);
this.id = id;
this.version = version;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(printer.syntax.pluginDependencySpec(id, version));
}
}
private static class DepSpec extends AbstractStatement {
final String configuration;
final List<String> deps;
DepSpec(String configuration, String comment, List<String> deps) {
super(comment);
this.configuration = configuration;
this.deps = deps;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
for (String dep : deps) {
printer.println(printer.syntax.dependencySpec(configuration, printer.syntax.string(dep)));
}
}
}
private static class PlatformDepSpec extends AbstractStatement {
private final String configuration;
private final String dep;
PlatformDepSpec(String configuration, String comment, String dep) {
super(comment);
this.configuration = configuration;
this.dep = dep;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(printer.syntax.dependencySpec(
configuration, "platform(" + printer.syntax.string(dep) + ")"
));
}
}
private static class ProjectDepSpec extends AbstractStatement {
private final String configuration;
private final String projectPath;
ProjectDepSpec(String configuration, String comment, String projectPath) {
super(comment);
this.configuration = configuration;
this.projectPath = projectPath;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(printer.syntax.dependencySpec(configuration, "project(" + printer.syntax.string(projectPath) + ")"));
}
}
private interface ConfigSelector {
@Nullable
String codeBlockSelectorFor(Syntax syntax);
}
private static class TaskSelector implements ConfigSelector {
final String taskName;
final String taskType;
private TaskSelector(String taskName, String taskType) {
this.taskName = taskName;
this.taskType = taskType;
}
@Nullable
@Override
public String codeBlockSelectorFor(Syntax syntax) {
return syntax.taskSelector(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TaskSelector that = (TaskSelector) o;
return Objects.equal(taskName, that.taskName) && Objects.equal(taskType, that.taskType);
}
@Override
public int hashCode() {
return Objects.hashCode(taskName, taskType);
}
}
private static class TaskTypeSelector implements ConfigSelector {
final String taskType;
TaskTypeSelector(String taskType) {
this.taskType = taskType;
}
@Nullable
@Override
public String codeBlockSelectorFor(Syntax syntax) {
return syntax.taskByTypeSelector(taskType);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TaskTypeSelector that = (TaskTypeSelector) o;
return Objects.equal(taskType, that.taskType);
}
@Override
public int hashCode() {
return taskType.hashCode();
}
}
private static class ConventionSelector implements ConfigSelector {
final String conventionName;
private ConventionSelector(String conventionName) {
this.conventionName = conventionName;
}
@Override
public String codeBlockSelectorFor(Syntax syntax) {
return syntax.conventionSelector(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConventionSelector that = (ConventionSelector) o;
return Objects.equal(conventionName, that.conventionName);
}
@Override
public int hashCode() {
return Objects.hashCode(conventionName);
}
}
/**
* Represents a statement in a script. Each statement has an optional comment that explains its purpose.
*/
private interface Statement {
enum Type {Empty, Single, Group}
@Nullable
String getComment();
/**
* Returns details of the size of this statement. Returns {@link Type#Empty} when this statement is empty and should not be included in the script.
*/
Type type();
/**
* Writes this statement to the given printer. Should not write the comment. Called only when {@link #type()} returns a value != {@link Type#Empty}
*/
void writeCodeTo(PrettyPrinter printer);
}
private static abstract class AbstractStatement implements Statement {
final String comment;
AbstractStatement(@Nullable String comment) {
this.comment = comment;
}
@Nullable
@Override
public String getComment() {
return comment;
}
@Override
public Type type() {
return Type.Single;
}
}
private static class MethodInvocation extends AbstractStatement {
final MethodInvocationExpression invocationExpression;
private MethodInvocation(String comment, MethodInvocationExpression invocationExpression) {
super(comment);
this.invocationExpression = invocationExpression;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(invocationExpression.with(printer.syntax));
}
}
private static class ContainerElement extends AbstractStatement implements ExpressionValue {
private final String comment;
private final String container;
private final String elementName;
@Nullable
private final String varName;
@Nullable
private final String elementType;
private final ScriptBlockImpl body = new ScriptBlockImpl();
public ContainerElement(String comment, String container, String elementName, @Nullable String elementType, @Nullable String varName) {
super(null);
this.comment = comment;
this.container = container;
this.elementName = elementName;
this.elementType = elementType;
this.varName = varName;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
Statement statement = printer.syntax.createContainerElement(comment, container, elementName, elementType, varName, body.statements);
printer.printStatement(statement);
}
@Override
public String with(Syntax syntax) {
return syntax.referenceCreatedContainerElement(container, elementName, varName);
}
}
private static class PropertyAssignment extends AbstractStatement {
final String propertyName;
final ExpressionValue propertyValue;
final boolean legacyProperty;
private PropertyAssignment(String comment, String propertyName, ExpressionValue propertyValue, boolean legacyProperty) {
super(comment);
this.propertyName = propertyName;
this.propertyValue = propertyValue;
this.legacyProperty = legacyProperty;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(printer.syntax.propertyAssignment(this));
}
}
private static class SingleLineComment extends AbstractStatement {
private SingleLineComment(String comment) {
super(comment);
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
// NO OP
}
}
/**
* Represents the contents of a block.
*/
private interface BlockBody {
void writeBodyTo(PrettyPrinter printer);
List<Statement> getStatements();
}
private static class BlockStatement implements Statement {
private final String comment;
final String blockSelector;
final ScriptBlockImpl body = new ScriptBlockImpl();
BlockStatement(String blockSelector) {
this(null, blockSelector);
}
BlockStatement(@Nullable String comment, String blockSelector) {
this.comment = comment;
this.blockSelector = blockSelector;
}
@Nullable
@Override
public String getComment() {
return comment;
}
@Override
public Type type() {
return body.type();
}
void add(Statement statement) {
body.add(statement);
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.printBlock(blockSelector, body);
}
}
private static class ScriptBlock extends BlockStatement {
ScriptBlock(String comment, String blockSelector) {
super(comment, blockSelector);
}
@Override
public Type type() {
// Always treat as non-empty
return Type.Group;
}
}
private static class RepositoriesBlock extends BlockStatement implements RepositoriesBuilder {
private final BuildScriptBuilder builder;
RepositoriesBlock(final BuildScriptBuilder builder) {
super("repositories");
this.builder = builder;
}
@Override
public void mavenLocal(String comment) {
add(new MethodInvocation(comment, new MethodInvocationExpression("mavenLocal")));
}
@Override
public void mavenCentral(@Nullable String comment) {
add(new MethodInvocation(comment, new MethodInvocationExpression("mavenCentral")));
}
@Override
public void gradlePluginPortal(@Nullable String comment) {
add(new MethodInvocation(comment, new MethodInvocationExpression("gradlePluginPortal")));
}
@Override
public void maven(String comment, String url) {
add(new MavenRepoExpression(comment, url, builder));
}
}
private static class DependenciesBlock implements DependenciesBuilder, Statement, BlockBody {
final ListMultimap<String, Statement> dependencies = MultimapBuilder.linkedHashKeys().arrayListValues().build();
final ListMultimap<String, Statement> constraints = MultimapBuilder.linkedHashKeys().arrayListValues().build();
@Override
public void dependency(String configuration, @Nullable String comment, String... dependencies) {
this.dependencies.put(configuration, new DepSpec(configuration, comment, Arrays.asList(dependencies)));
}
@Override
public void dependencyConstraint(String configuration, @Nullable String comment, String... constraints) {
this.constraints.put(configuration, new DepSpec(configuration, comment, Arrays.asList(constraints)));
}
@Override
public void platformDependency(String configuration, @Nullable String comment, String dependency) {
this.dependencies.put(configuration, new PlatformDepSpec(configuration, comment, dependency));
}
@Override
public void projectDependency(String configuration, @Nullable String comment, String projectPath) {
this.dependencies.put(configuration, new ProjectDepSpec(configuration, comment, projectPath));
}
@Nullable
@Override
public String getComment() {
return null;
}
@Override
public Type type() {
return dependencies.isEmpty() && constraints.isEmpty() ? Type.Empty : Type.Group;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.printBlock("dependencies", this);
}
@Override
public void writeBodyTo(PrettyPrinter printer) {
if (!this.constraints.isEmpty()) {
ScriptBlockImpl constraintsBlock = new ScriptBlockImpl();
for (String config : this.constraints.keySet()) {
for (Statement constraintSpec : this.constraints.get(config)) {
constraintsBlock.add(constraintSpec);
}
}
printer.printBlock("constraints", constraintsBlock);
}
for (String config : dependencies.keySet()) {
for (Statement depSpec : dependencies.get(config)) {
printer.printStatement(depSpec);
}
}
}
@Override
public List<Statement> getStatements() {
List<Statement> statements = new ArrayList<>();
if (!constraints.isEmpty()) {
ScriptBlock constraintsBlock = new ScriptBlock(null, "constraints");
for (String config : constraints.keySet()) {
for(Statement statement : constraints.get(config)) {
constraintsBlock.add(statement);
}
}
statements.add(constraintsBlock);
}
for (String config : dependencies.keySet()) {
statements.addAll(dependencies.get(config));
}
return statements;
}
}
private static class MavenRepoExpression extends AbstractStatement {
private final URI uri;
private final BuildScriptBuilder builder;
MavenRepoExpression(@Nullable String comment, String url, BuildScriptBuilder builder) {
super(comment);
this.uri = uriFromString(url);
this.builder = builder;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
builder.mavenRepoURLHandler.handleURL(uri, printer);
}
}
public static class ScriptBlockImpl implements ScriptBlockBuilder, BlockBody {
final List<Statement> statements = new ArrayList<>();
public void add(Statement statement) {
statements.add(statement);
}
@Override
public List<Statement> getStatements() {
return statements;
}
public Statement.Type type() {
for (Statement statement : statements) {
if (statement.type() != Statement.Type.Empty) {
return Statement.Type.Group;
}
}
return Statement.Type.Empty;
}
@Override
public void writeBodyTo(PrettyPrinter printer) {
printer.printStatements(statements);
}
@Override
public void propertyAssignment(String comment, String propertyName, Object propertyValue, boolean legacyProperty) {
statements.add(new PropertyAssignment(comment, propertyName, expressionValue(propertyValue), legacyProperty));
}
@Override
public void methodInvocation(String comment, String methodName, Object... methodArgs) {
statements.add(new MethodInvocation(comment, new MethodInvocationExpression(null, methodName, expressionValues(methodArgs))));
}
@Override
public void methodInvocation(@Nullable String comment, Expression target, String methodName, Object... methodArgs) {
statements.add(new MethodInvocation(comment, new MethodInvocationExpression(expressionValue(target), methodName, expressionValues(methodArgs))));
}
@Override
public ScriptBlockBuilder block(String comment, String methodName) {
ScriptBlock scriptBlock = new ScriptBlock(comment, methodName);
statements.add(scriptBlock);
return scriptBlock.body;
}
@Override
public void block(@Nullable String comment, String methodName, Action<? super ScriptBlockBuilder> blockContentsBuilder) {
blockContentsBuilder.execute(block(comment, methodName));
}
@Override
public Expression containerElement(@Nullable String comment, String container, String elementName, @Nullable String elementType, Action<? super ScriptBlockBuilder> blockContentsBuilder) {
ContainerElement containerElement = new ContainerElement(comment, container, elementName, elementType, null);
statements.add(containerElement);
blockContentsBuilder.execute(containerElement.body);
return containerElement;
}
@Override
public Expression propertyExpression(String value) {
return new LiteralValue(value);
}
@Override
public void comment(String comment) {
statements.add(new SingleLineComment(comment));
}
}
private static class TopLevelBlock extends ScriptBlockImpl {
final BlockStatement plugins = new BlockStatement("plugins");
final RepositoriesBlock repositories;
final DependenciesBlock dependencies = new DependenciesBlock();
final ConfigurationStatements<TaskTypeSelector> taskTypes = new ConfigurationStatements<>();
final ConfigurationStatements<TaskSelector> tasks = new ConfigurationStatements<>();
final ConfigurationStatements<ConventionSelector> conventions = new ConfigurationStatements<>();
private TopLevelBlock(BuildScriptBuilder builder) {
repositories = new RepositoriesBlock(builder);
}
@Override
public void writeBodyTo(PrettyPrinter printer) {
printer.printStatement(plugins);
printer.printStatement(repositories);
printer.printStatement(dependencies);
super.writeBodyTo(printer);
printer.printStatement(conventions);
printer.printStatement(taskTypes);
printer.printStatement(tasks);
}
public List<String> extractComments() {
List<String> comments = new ArrayList<>();
collectComments(plugins.body, comments);
collectComments(repositories.body, comments);
collectComments(dependencies, comments);
for (Statement otherBlock : getStatements()) {
if (otherBlock instanceof BlockStatement) {
collectComments(((BlockStatement) otherBlock).body, comments);
}
}
return comments;
}
private void collectComments(BlockBody body, List<String> comments) {
for (Statement statement : body.getStatements()) {
if (statement.getComment() != null) {
comments.add(statement.getComment());
}
}
}
}
private static class TaskRegistration implements Statement, ExpressionValue {
final String taskName;
final String taskType;
final String comment;
final ScriptBlockImpl body = new ScriptBlockImpl();
TaskRegistration(@Nullable String comment, String taskName, String taskType) {
this.comment = comment;
this.taskName = taskName;
this.taskType = taskType;
}
@Nullable
@Override
public String getComment() {
return comment;
}
@Override
public Type type() {
return Type.Group;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.printBlock(printer.syntax.taskRegistration(taskName, taskType), body);
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return syntax.referenceRegisteredTask(taskName);
}
}
private static class ConfigurationStatements<T extends ConfigSelector> implements Statement {
final ListMultimap<T, Statement> blocks = MultimapBuilder.linkedHashKeys().arrayListValues().build();
void add(T selector, Statement statement) {
blocks.put(selector, statement);
}
@Nullable
@Override
public String getComment() {
return null;
}
@Override
public Type type() {
return blocks.isEmpty() ? Type.Empty : Type.Single;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
for (T configSelector : blocks.keySet()) {
String selector = configSelector.codeBlockSelectorFor(printer.syntax);
if (selector != null) {
BlockStatement statement = new BlockStatement(selector);
statement.body.statements.addAll(blocks.get(configSelector));
printer.printStatement(statement);
} else {
printer.printStatements(blocks.get(configSelector));
}
}
}
}
private static final class PrettyPrinter {
private final Syntax syntax;
private final PrintWriter writer;
private final boolean externalComments;
private String indent = "";
private String eolComment = null;
private int commentCount = 0;
private boolean needSeparatorLine = true;
private boolean firstStatementOfBlock = false;
private boolean hasSeparatorLine = false;
PrettyPrinter(Syntax syntax, PrintWriter writer, boolean externalComments) {
this.syntax = syntax;
this.writer = writer;
this.externalComments = externalComments;
}
public void printFileHeader(Collection<String> lines) {
if (externalComments) {
return;
}
println("/*");
println(" * This file was generated by the Gradle 'init' task.");
if (!lines.isEmpty()) {
println(" *");
for (String headerLine : lines) {
if (headerLine.isEmpty()) {
println(" *");
} else {
println(" * " + headerLine);
}
}
}
println(" */");
}
public void printBlock(String blockSelector, BlockBody blockBody) {
String indentBefore = indent;
println(blockSelector + " {");
indent = indent + " ";
needSeparatorLine = false;
firstStatementOfBlock = true;
blockBody.writeBodyTo(this);
indent = indentBefore;
println("}");
// Write a line separator after any block
needSeparatorLine = true;
}
public void printStatements(List<? extends Statement> statements) {
for (Statement statement : statements) {
printStatement(statement);
}
}
private void printStatementSeparator() {
if (needSeparatorLine && !hasSeparatorLine) {
println();
needSeparatorLine = false;
}
}
private void printStatement(Statement statement) {
Statement.Type type = statement.type();
if (type == Statement.Type.Empty) {
return;
}
boolean hasComment = statement.getComment() != null;
// Add separators before and after anything with a comment or that is a block or group of statements
boolean needsSeparator = hasComment || type == Statement.Type.Group;
if (needsSeparator && !firstStatementOfBlock) {
needSeparatorLine = true;
}
printStatementSeparator();
if (hasComment) {
if (externalComments) {
commentCount++;
eolComment = " // <" + commentCount + ">";
} else {
for (String line : splitComment(statement.getComment())) {
println("// " + line);
}
}
}
statement.writeCodeTo(this);
firstStatementOfBlock = false;
if (needsSeparator) {
needSeparatorLine = true;
}
}
private void println(String s) {
if (!indent.isEmpty()) {
writer.print(indent);
}
if (eolComment != null) {
writer.println(s + eolComment);
eolComment = null;
} else {
writer.println(s);
}
hasSeparatorLine = false;
}
private void println() {
writer.println();
hasSeparatorLine = true;
}
}
private interface Syntax {
String pluginDependencySpec(String pluginId, @Nullable String version);
@SuppressWarnings("unused")
String nestedPluginDependencySpec(String pluginId, @Nullable String version);
String dependencySpec(String config, String notation);
String propertyAssignment(PropertyAssignment expression);
@Nullable
String conventionSelector(ConventionSelector selector);
String taskSelector(TaskSelector selector);
String taskByTypeSelector(String taskType);
String string(String string);
String taskRegistration(String taskName, String taskType);
String referenceRegisteredTask(String taskName);
String mapLiteral(Map<String, ExpressionValue> map);
String firstArg(ExpressionValue argument);
Statement createContainerElement(@Nullable String comment, String container, String elementName, @Nullable String elementType, @Nullable String varName, List<Statement> body);
String referenceCreatedContainerElement(String container, String elementName, @Nullable String varName);
String containerElement(String container, String element);
void configureConventionPlugin(@Nullable String comment, BlockStatement plugins, RepositoriesBlock repositories);
}
private static final class KotlinSyntax implements Syntax {
@Override
public String string(String string) {
return '"' + string + '"';
}
@Override
public String mapLiteral(Map<String, ExpressionValue> map) {
StringBuilder builder = new StringBuilder();
builder.append("mapOf(");
boolean first = true;
for (Map.Entry<String, ExpressionValue> entry : map.entrySet()) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(string(entry.getKey()));
builder.append(" to ");
builder.append(entry.getValue().with(this));
}
builder.append(")");
return builder.toString();
}
@Override
public String firstArg(ExpressionValue argument) {
return argument.with(this);
}
@Override
public String pluginDependencySpec(String pluginId, @Nullable String version) {
if (version != null) {
return "id(\"" + pluginId + "\") version \"" + version + "\"";
} else if (pluginId.contains(".")) {
return "id(\"" + pluginId + "\")";
}
return pluginId.matches("[a-z]+") ? pluginId : "`" + pluginId + "`";
}
@Override
public String nestedPluginDependencySpec(String pluginId, @Nullable String version) {
if (version != null) {
throw new UnsupportedOperationException();
}
return "plugins.apply(\"" + pluginId + "\")";
}
@Override
public String dependencySpec(String config, String notation) {
return config + "(" + notation + ")";
}
@Override
public String propertyAssignment(PropertyAssignment expression) {
String propertyName = expression.propertyName;
ExpressionValue propertyValue = expression.propertyValue;
if (expression.legacyProperty) {
if (propertyValue.isBooleanType()) {
return booleanPropertyNameFor(propertyName) + " = " + propertyValue.with(this);
}
return propertyName + " = " + propertyValue.with(this);
} else {
return propertyName + ".set(" + propertyValue.with(this) + ")";
}
}
// In Kotlin:
//
// > Boolean accessor methods (where the name of the getter starts with is and the name of
// > the setter starts with set) are represented as properties which have the same name as
// > the getter method. Boolean properties are visible with a `is` prefix in Kotlin
//
// https://kotlinlang.org/docs/reference/java-interop.html#getters-and-setters
//
// This code assumes all configurable Boolean property getters follow the `is` prefix convention.
//
private String booleanPropertyNameFor(String propertyName) {
return "is" + StringUtils.capitalize(propertyName);
}
@Override
public String conventionSelector(ConventionSelector selector) {
return selector.conventionName;
}
@Override
public String taskSelector(TaskSelector selector) {
return "tasks." + selector.taskName;
}
@Override
public String taskByTypeSelector(String taskType) {
return "tasks.withType<" + taskType + ">()";
}
@Override
public String taskRegistration(String taskName, String taskType) {
return "val " + taskName + " by tasks.registering(" + taskType + "::class)";
}
@Override
public String referenceRegisteredTask(String taskName) {
return taskName;
}
@Override
public Statement createContainerElement(String comment, String container, String elementName, @Nullable String elementType, String varName, List<Statement> body) {
String literal;
if (varName == null) {
if (elementType == null) {
literal = "val " + elementName + " by " + container + ".creating";
} else {
literal = container + ".create<" + elementType + ">(" + string(elementName) + ")";
}
} else {
if (elementType == null) {
literal = "val " + varName + " = " + container + ".create(" + string(elementName) + ")";
} else {
literal = "val " + varName + " = " + container + ".create<" + elementType + ">(" + string(elementName) + ")";
}
}
BlockStatement blockStatement = new ScriptBlock(comment, literal);
for (Statement statement : body) {
blockStatement.add(statement);
}
return blockStatement;
}
@Override
public String referenceCreatedContainerElement(String container, String elementName, String varName) {
if (varName == null) {
return elementName;
} else {
return varName;
}
}
@Override
public String containerElement(String container, String element) {
return container + "[" + string(element) + "]";
}
@Override
public void configureConventionPlugin(@Nullable String comment, BlockStatement plugins, RepositoriesBlock repositories) {
plugins.add(new PluginSpec("kotlin-dsl", null, comment));
}
}
private static final class GroovySyntax implements Syntax {
@Override
public String string(String string) {
return "'" + string + "'";
}
@Override
public String mapLiteral(Map<String, ExpressionValue> map) {
StringBuilder builder = new StringBuilder();
builder.append("[");
addEntries(map, builder);
builder.append("]");
return builder.toString();
}
private void addEntries(Map<String, ExpressionValue> map, StringBuilder builder) {
boolean first = true;
for (Map.Entry<String, ExpressionValue> entry : map.entrySet()) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(entry.getKey());
builder.append(": ");
builder.append(entry.getValue().with(this));
}
}
@Override
public String firstArg(ExpressionValue argument) {
if (argument instanceof MapLiteralValue) {
MapLiteralValue literalValue = (MapLiteralValue) argument;
StringBuilder builder = new StringBuilder();
addEntries(literalValue.literal, builder);
return builder.toString();
} else {
return argument.with(this);
}
}
@Override
public String pluginDependencySpec(String pluginId, @Nullable String version) {
if (version != null) {
return "id '" + pluginId + "' version '" + version + "'";
}
return "id '" + pluginId + "'";
}
@Override
public String nestedPluginDependencySpec(String pluginId, @Nullable String version) {
if (version != null) {
throw new UnsupportedOperationException();
}
return "apply plugin: '" + pluginId + "'";
}
@Override
public String dependencySpec(String config, String notation) {
return config + " " + notation;
}
@Override
public String propertyAssignment(PropertyAssignment expression) {
String propertyName = expression.propertyName;
ExpressionValue propertyValue = expression.propertyValue;
return propertyName + " = " + propertyValue.with(this);
}
@Override
public String conventionSelector(ConventionSelector selector) {
return null;
}
@Override
public String taskSelector(TaskSelector selector) {
return "tasks.named('" + selector.taskName + "')";
}
@Override
public String taskByTypeSelector(String taskType) {
return "tasks.withType(" + taskType + ")";
}
@Override
public String taskRegistration(String taskName, String taskType) {
return "tasks.register('" + taskName + "', " + taskType + ")";
}
@Override
public String referenceRegisteredTask(String taskName) {
return "tasks." + taskName;
}
@Override
public Statement createContainerElement(String comment, String container, String elementName, @Nullable String elementType, String varName, List<Statement> body) {
ScriptBlock outerBlock = new ScriptBlock(comment, container);
ScriptBlock innerBlock = new ScriptBlock(null, elementType == null ? elementName : elementName + "(" + elementType + ")");
outerBlock.add(innerBlock);
for (Statement statement : body) {
innerBlock.add(statement);
}
return outerBlock;
}
@Override
public String referenceCreatedContainerElement(String container, String elementName, String varName) {
return container + "." + elementName;
}
@Override
public String containerElement(String container, String element) {
return container + "." + element;
}
@Override
public void configureConventionPlugin(@Nullable String comment, BlockStatement plugins, RepositoriesBlock repositories) {
plugins.add(new PluginSpec("groovy-gradle-plugin", null, comment));
}
}
private interface MavenRepositoryURLHandler {
void handleURL(URI repoLocation, PrettyPrinter printer);
static MavenRepositoryURLHandler forInsecureProtocolOption(InsecureProtocolOption insecureProtocolOption, BuildInitDsl dsl, DocumentationRegistry documentationRegistry) {
switch (insecureProtocolOption) {
case FAIL:
return new FailingHandler(documentationRegistry);
case WARN:
return new WarningHandler(dsl, documentationRegistry);
case ALLOW:
return new AllowingHandler();
case UPGRADE:
return new UpgradingHandler();
default:
throw new IllegalStateException(String.format("Unknown handler: '%s'.", insecureProtocolOption));
}
}
abstract class AbstractMavenRepositoryURLHandler implements MavenRepositoryURLHandler {
@Override
public void handleURL(URI repoLocation, PrettyPrinter printer) {
ScriptBlockImpl statements = new ScriptBlockImpl();
if (GUtil.isSecureUrl(repoLocation)) {
handleSecureURL(repoLocation, statements);
} else {
LOGGER.warn("Repository URL: '{}' uses an insecure protocol.", repoLocation);
handleInsecureURL(repoLocation, statements);
}
printer.printBlock("maven", statements);
}
protected void handleSecureURL(URI repoLocation, BuildScriptBuilder.ScriptBlockImpl statements) {
statements.propertyAssignment(null, "url", new MethodInvocationExpression(null, "uri", Collections.singletonList(new StringValue(repoLocation.toString()))), true);
}
protected abstract void handleInsecureURL(URI repoLocation, BuildScriptBuilder.ScriptBlockImpl statements);
}
class FailingHandler extends AbstractMavenRepositoryURLHandler {
private final DocumentationRegistry documentationRegistry;
public FailingHandler(DocumentationRegistry documentationRegistry) {
this.documentationRegistry = documentationRegistry;
}
@Override
protected void handleInsecureURL(URI repoLocation, ScriptBlockImpl statements) {
LOGGER.error("Gradle found an insecure protocol in a repository definition. The current strategy for handling insecure URLs is to fail. For more options, see {}.", documentationRegistry.getDocumentationFor("build_init_plugin", "allow_insecure"));
throw new GradleException(String.format("Build aborted due to insecure protocol in repository: %s", repoLocation));
}
}
class WarningHandler extends AbstractMavenRepositoryURLHandler {
private final BuildInitDsl dsl;
private final DocumentationRegistry documentationRegistry;
public WarningHandler(BuildInitDsl dsl, DocumentationRegistry documentationRegistry) {
this.dsl = dsl;
this.documentationRegistry = documentationRegistry;
}
@Override
protected void handleInsecureURL(URI repoLocation, BuildScriptBuilder.ScriptBlockImpl statements) {
LOGGER.warn("Gradle found an insecure protocol in a repository definition. You will have to opt into allowing insecure protocols in the generated build file. See {}.", documentationRegistry.getDocumentationFor("build_init_plugin", "allow_insecure"));
statements.propertyAssignment(null, "url", new BuildScriptBuilder.MethodInvocationExpression(null, "uri", Collections.singletonList(new BuildScriptBuilder.StringValue(repoLocation.toString()))), true);
statements.comment(buildAllowInsecureProtocolComment(dsl));
}
private String buildAllowInsecureProtocolComment(BuildInitDsl dsl) {
final PropertyAssignment assignment = new PropertyAssignment(null, "allowInsecureProtocol", new BuildScriptBuilder.LiteralValue(true), true);
final StringWriter result = new StringWriter();
try (PrintWriter writer = new PrintWriter(result)) {
PrettyPrinter printer = new PrettyPrinter(syntaxFor(dsl), writer, false);
assignment.writeCodeTo(printer);
return result.toString();
} catch (Exception e) {
throw new GradleException("Could not write comment.", e);
}
}
}
class UpgradingHandler extends AbstractMavenRepositoryURLHandler {
@Override
protected void handleInsecureURL(URI repoLocation, BuildScriptBuilder.ScriptBlockImpl statements) {
final URI secureUri;
try {
secureUri = GUtil.toSecureUrl(repoLocation);
} catch (final IllegalArgumentException e) {
throw new GradleException(String.format("Can't upgrade insecure protocol for URL: '%s' as no replacement protocol exists.", repoLocation));
}
LOGGER.warn("Upgrading protocol to '{}'.", secureUri);
statements.propertyAssignment(null, "url", new BuildScriptBuilder.MethodInvocationExpression(null, "uri", Collections.singletonList(new BuildScriptBuilder.StringValue(secureUri.toString()))), true);
}
}
class AllowingHandler extends AbstractMavenRepositoryURLHandler {
@Override
protected void handleInsecureURL(URI repoLocation, BuildScriptBuilder.ScriptBlockImpl statements) {
statements.propertyAssignment(null, "url", new BuildScriptBuilder.MethodInvocationExpression(null, "uri", Collections.singletonList(new BuildScriptBuilder.StringValue(repoLocation.toString()))), true);
statements.propertyAssignment(null, "allowInsecureProtocol", new BuildScriptBuilder.LiteralValue(true), true);
}
}
}
}
| subprojects/build-init/src/main/java/org/gradle/buildinit/plugins/internal/BuildScriptBuilder.java | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.buildinit.plugins.internal;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import org.apache.commons.lang.StringUtils;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.file.Directory;
import org.gradle.api.internal.DocumentationRegistry;
import org.gradle.buildinit.plugins.internal.modifiers.BuildInitDsl;
import org.gradle.buildinit.plugins.internal.modifiers.InsecureProtocolOption;
import org.gradle.internal.Cast;
import org.gradle.internal.UncheckedException;
import org.gradle.util.internal.GFileUtils;
import org.gradle.util.internal.GUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Assembles the parts of a build script.
*/
@SuppressWarnings("UnusedReturnValue")
public class BuildScriptBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(BuildScriptBuilder.class);
private final BuildInitDsl dsl;
private final String fileNameWithoutExtension;
private boolean externalComments;
private final InsecureProtocolHandler insecureProtocolHandler;
private final List<String> headerLines = new ArrayList<>();
private final TopLevelBlock block;
public static BuildScriptBuilder forNewProjects(BuildInitDsl dsl, DocumentationRegistry documentationRegistry, String fileNameWithoutExtension) {
return new BuildScriptBuilder(dsl, documentationRegistry, fileNameWithoutExtension, InsecureProtocolOption.FAIL);
}
public static BuildScriptBuilder forMavenConversion(BuildInitDsl dsl, DocumentationRegistry documentationRegistry, String fileNameWithoutExtension, InsecureProtocolOption insecureProtocolHandler) {
return new BuildScriptBuilder(dsl, documentationRegistry, fileNameWithoutExtension, insecureProtocolHandler);
}
private BuildScriptBuilder(BuildInitDsl dsl, DocumentationRegistry documentationRegistry, String fileNameWithoutExtension, InsecureProtocolOption insecureProtocolHandler) {
this.dsl = dsl;
this.fileNameWithoutExtension = fileNameWithoutExtension;
this.insecureProtocolHandler = InsecureProtocolHandler.forOption(insecureProtocolHandler, dsl, documentationRegistry);
block = new TopLevelBlock(this);
}
public BuildScriptBuilder withExternalComments() {
this.externalComments = true;
return this;
}
public String getFileNameWithoutExtension() {
return fileNameWithoutExtension;
}
/**
* Adds a comment to the header of the file.
*/
public BuildScriptBuilder fileComment(String comment) {
headerLines.addAll(splitComment(comment));
return this;
}
private static List<String> splitComment(String comment) {
return Splitter.on("\n").splitToList(comment.trim());
}
private static URI uriFromString(String uriAsString) {
try {
return new URI(uriAsString);
} catch (URISyntaxException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
/**
* Adds a plugin to be applied
*
* @param comment A description of why the plugin is required
*/
public BuildScriptBuilder plugin(@Nullable String comment, String pluginId) {
block.plugins.add(new PluginSpec(pluginId, null, comment));
return this;
}
/**
* Adds the plugin and config needed to support writing pre-compiled script plugins in the selected DSL in this project.
*/
public BuildScriptBuilder conventionPluginSupport(@Nullable String comment) {
Syntax syntax = syntaxFor(dsl);
block.repositories.gradlePluginPortal("Use the plugin portal to apply community plugins in convention plugins.");
syntax.configureConventionPlugin(comment, block.plugins, block.repositories);
return this;
}
/**
* Adds a plugin to be applied
*
* @param comment A description of why the plugin is required
*/
public BuildScriptBuilder plugin(@Nullable String comment, String pluginId, String version) {
block.plugins.add(new PluginSpec(pluginId, version, comment));
return this;
}
/**
* Adds one or more external dependencies to the specified configuration.
*
* @param configuration The configuration where the dependency should be added
* @param comment A description of why the dependencies are required
* @param dependencies the dependencies, in string notation
*/
public BuildScriptBuilder dependency(String configuration, @Nullable String comment, String... dependencies) {
dependencies().dependency(configuration, comment, dependencies);
return this;
}
/**
* Adds one or more external implementation dependencies.
*
* @param comment A description of why the dependencies are required
* @param dependencies The dependencies, in string notation
*/
public BuildScriptBuilder implementationDependency(@Nullable String comment, String... dependencies) {
return dependency("implementation", comment, dependencies);
}
/**
* Adds one or more dependency constraints to the implementation scope.
*
* @param comment A description of why the constraints are required
* @param dependencies The constraints, in string notation
*/
public BuildScriptBuilder implementationDependencyConstraint(@Nullable String comment, String... dependencies) {
dependencies().dependencyConstraint("implementation", comment, dependencies);
return this;
}
/**
* Adds one or more external test implementation dependencies.
*
* @param comment A description of why the dependencies are required
* @param dependencies The dependencies, in string notation
*/
public BuildScriptBuilder testImplementationDependency(@Nullable String comment, String... dependencies) {
return dependency("testImplementation", comment, dependencies);
}
/**
* Adds one or more external test runtime only dependencies.
*
* @param comment A description of why the dependencies are required
* @param dependencies The dependencies, in string notation
*/
public BuildScriptBuilder testRuntimeOnlyDependency(@Nullable String comment, String... dependencies) {
return dependency("testRuntimeOnly", comment, dependencies);
}
/**
* Creates a method invocation expression, to use as a method argument or the RHS of a property assignment.
*/
public Expression methodInvocationExpression(String methodName, Object... methodArgs) {
return new MethodInvocationExpression(null, methodName, expressionValues(methodArgs));
}
/**
* Creates a property expression, to use as a method argument or the RHS of a property assignment.
*/
public Expression propertyExpression(String value) {
return new LiteralValue(value);
}
/**
* Creates a property expression, to use as a method argument or the RHS of a property assignment.
*/
public Expression propertyExpression(Expression expression, String value) {
return new ChainedPropertyExpression((ExpressionValue) expression, new LiteralValue(value));
}
/**
* Creates an expression that references an element in a container.
*/
public Expression containerElementExpression(String container, String element) {
return new ContainerElementExpression(container, element);
}
private static List<ExpressionValue> expressionValues(Object... expressions) {
List<ExpressionValue> result = new ArrayList<>(expressions.length);
for (Object expression : expressions) {
result.add(expressionValue(expression));
}
return result;
}
private static Map<String, ExpressionValue> expressionMap(Map<String, ?> expressions) {
LinkedHashMap<String, ExpressionValue> result = new LinkedHashMap<>();
for (Map.Entry<String, ?> entry : expressions.entrySet()) {
result.put(entry.getKey(), expressionValue(entry.getValue()));
}
return result;
}
private static ExpressionValue expressionValue(Object expression) {
if (expression instanceof CharSequence) {
return new StringValue((CharSequence) expression);
}
if (expression instanceof ExpressionValue) {
return (ExpressionValue) expression;
}
if (expression instanceof Number || expression instanceof Boolean) {
return new LiteralValue(expression);
}
if (expression instanceof Map) {
return new MapLiteralValue(expressionMap(Cast.uncheckedNonnullCast(expression)));
}
if (expression instanceof Enum) {
return new EnumValue(expression);
}
throw new IllegalArgumentException("Don't know how to treat " + expression + " as an expression.");
}
/**
* Allows repositories to be added to this script.
*/
public RepositoriesBuilder repositories() {
return block.repositories;
}
/**
* Allows dependencies to be added to this script.
*/
public DependenciesBuilder dependencies() {
return block.dependencies;
}
/**
* Adds a top level method invocation statement.
*
* @return this
*/
public BuildScriptBuilder methodInvocation(@Nullable String comment, String methodName, Object... methodArgs) {
block.methodInvocation(comment, methodName, methodArgs);
return this;
}
/**
* Adds a top level method invocation statement.
*
* @return this
*/
public BuildScriptBuilder methodInvocation(@Nullable String comment, Expression target, String methodName, Object... methodArgs) {
block.methodInvocation(comment, target, methodName, methodArgs);
return this;
}
/**
* Adds a top level property assignment statement.
*
* @return this
*/
public BuildScriptBuilder propertyAssignment(@Nullable String comment, String propertyName, Object propertyValue) {
block.propertyAssignment(comment, propertyName, propertyValue, true);
return this;
}
/**
* Adds a top level block statement.
*
* @return The body of the block, to which further statements can be added.
*/
public ScriptBlockBuilder block(@Nullable String comment, String methodName) {
return block.block(comment, methodName);
}
/**
* Adds a top level block statement.
*/
public BuildScriptBuilder block(@Nullable String comment, String methodName, Action<? super ScriptBlockBuilder> blockContentBuilder) {
blockContentBuilder.execute(block.block(comment, methodName));
return this;
}
/**
* Adds a method invocation statement to the configuration of a particular task.
*/
public BuildScriptBuilder taskMethodInvocation(@Nullable String comment, String taskName, String taskType, String methodName, Object... methodArgs) {
block.tasks.add(
new TaskSelector(taskName, taskType),
new MethodInvocation(comment, new MethodInvocationExpression(null, methodName, expressionValues(methodArgs))));
return this;
}
/**
* Adds a property assignment statement to the configuration of a particular task.
*/
public BuildScriptBuilder taskPropertyAssignment(@Nullable String comment, String taskName, String taskType, String propertyName, Object propertyValue) {
block.tasks.add(
new TaskSelector(taskName, taskType),
new PropertyAssignment(comment, propertyName, expressionValue(propertyValue), true));
return this;
}
/**
* Adds a property assignment statement to the configuration of all tasks of a particular type.
*/
public BuildScriptBuilder taskPropertyAssignment(@Nullable String comment, String taskType, String propertyName, Object propertyValue) {
block.taskTypes.add(
new TaskTypeSelector(taskType),
new PropertyAssignment(comment, propertyName, expressionValue(propertyValue), true));
return this;
}
/**
* Registers a task.
*
* @return An expression that can be used to refer to the task later.
*/
public Expression taskRegistration(@Nullable String comment, String taskName, String taskType, Action<? super ScriptBlockBuilder> blockContentsBuilder) {
TaskRegistration registration = new TaskRegistration(comment, taskName, taskType);
block.add(registration);
blockContentsBuilder.execute(registration.body);
return registration;
}
/**
* Creates an element in the given container.
*
* @param varName A variable to use to reference the element, if required by the DSL. If {@code null}, then use the element name.
*
* @return An expression that can be used to refer to the element later in the script.
*/
public Expression createContainerElement(@Nullable String comment, String container, String elementName, @Nullable String varName) {
ContainerElement containerElement = new ContainerElement(comment, container, elementName, null, varName);
block.add(containerElement);
return containerElement;
}
public TemplateOperation create(Directory targetDirectory) {
return () -> {
File target = getTargetFile(targetDirectory);
GFileUtils.mkdirs(target.getParentFile());
try (PrintWriter writer = new PrintWriter(new FileWriter(target))) {
PrettyPrinter printer = new PrettyPrinter(syntaxFor(dsl), writer, externalComments);
printer.printFileHeader(headerLines);
block.writeBodyTo(printer);
} catch (Exception e) {
throw new GradleException("Could not generate file " + target + ".", e);
}
};
}
public List<String> extractComments() {
return block.extractComments();
}
private File getTargetFile(Directory targetDirectory) {
return targetDirectory.file(dsl.fileNameFor(fileNameWithoutExtension)).getAsFile();
}
private static Syntax syntaxFor(BuildInitDsl dsl) {
switch (dsl) {
case KOTLIN:
return new KotlinSyntax();
case GROOVY:
return new GroovySyntax();
default:
throw new IllegalStateException();
}
}
public interface Expression {
}
private interface ExpressionValue extends Expression {
boolean isBooleanType();
String with(Syntax syntax);
}
private static class ChainedPropertyExpression implements Expression, ExpressionValue {
private final ExpressionValue left;
private final ExpressionValue right;
public ChainedPropertyExpression(ExpressionValue left, ExpressionValue right) {
this.left = left;
this.right = right;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return left.with(syntax) + "." + right.with(syntax);
}
}
private static class StringValue implements ExpressionValue {
final CharSequence value;
StringValue(CharSequence value) {
this.value = value;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return syntax.string(value.toString());
}
}
private static class LiteralValue implements ExpressionValue {
final Object literal;
LiteralValue(Object literal) {
this.literal = literal;
}
@Override
public boolean isBooleanType() {
return literal instanceof Boolean;
}
@Override
public String with(Syntax syntax) {
return literal.toString();
}
}
private static class EnumValue implements ExpressionValue {
final Enum<?> literal;
EnumValue(Object literal) {
this.literal = Cast.uncheckedNonnullCast(literal);
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return literal.getClass().getSimpleName() + "." + literal.name();
}
}
private static class MapLiteralValue implements ExpressionValue {
final Map<String, ExpressionValue> literal;
public MapLiteralValue(Map<String, ExpressionValue> literal) {
this.literal = literal;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return syntax.mapLiteral(literal);
}
}
private static class MethodInvocationExpression implements ExpressionValue {
@Nullable
private final ExpressionValue target;
final String methodName;
final List<ExpressionValue> arguments;
MethodInvocationExpression(@Nullable ExpressionValue target, String methodName, List<ExpressionValue> arguments) {
this.target = target;
this.methodName = methodName;
this.arguments = arguments;
}
MethodInvocationExpression(String methodName) {
this(null, methodName, Collections.emptyList());
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
StringBuilder result = new StringBuilder();
if (target != null) {
result.append(target.with(syntax));
result.append('.');
}
result.append(methodName);
result.append("(");
for (int i = 0; i < arguments.size(); i++) {
ExpressionValue argument = arguments.get(i);
if (i == 0) {
result.append(syntax.firstArg(argument));
} else {
result.append(", ");
result.append(argument.with(syntax));
}
}
result.append(")");
return result.toString();
}
}
private static class ContainerElementExpression implements ExpressionValue {
private final String container;
private final String element;
public ContainerElementExpression(String container, String element) {
this.container = container;
this.element = element;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return syntax.containerElement(container, element);
}
}
private static class PluginSpec extends AbstractStatement {
final String id;
@Nullable
final String version;
PluginSpec(String id, @Nullable String version, String comment) {
super(comment);
this.id = id;
this.version = version;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(printer.syntax.pluginDependencySpec(id, version));
}
}
private static class DepSpec extends AbstractStatement {
final String configuration;
final List<String> deps;
DepSpec(String configuration, String comment, List<String> deps) {
super(comment);
this.configuration = configuration;
this.deps = deps;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
for (String dep : deps) {
printer.println(printer.syntax.dependencySpec(configuration, printer.syntax.string(dep)));
}
}
}
private static class PlatformDepSpec extends AbstractStatement {
private final String configuration;
private final String dep;
PlatformDepSpec(String configuration, String comment, String dep) {
super(comment);
this.configuration = configuration;
this.dep = dep;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(printer.syntax.dependencySpec(
configuration, "platform(" + printer.syntax.string(dep) + ")"
));
}
}
private static class ProjectDepSpec extends AbstractStatement {
private final String configuration;
private final String projectPath;
ProjectDepSpec(String configuration, String comment, String projectPath) {
super(comment);
this.configuration = configuration;
this.projectPath = projectPath;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(printer.syntax.dependencySpec(configuration, "project(" + printer.syntax.string(projectPath) + ")"));
}
}
private interface ConfigSelector {
@Nullable
String codeBlockSelectorFor(Syntax syntax);
}
private static class TaskSelector implements ConfigSelector {
final String taskName;
final String taskType;
private TaskSelector(String taskName, String taskType) {
this.taskName = taskName;
this.taskType = taskType;
}
@Nullable
@Override
public String codeBlockSelectorFor(Syntax syntax) {
return syntax.taskSelector(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TaskSelector that = (TaskSelector) o;
return Objects.equal(taskName, that.taskName) && Objects.equal(taskType, that.taskType);
}
@Override
public int hashCode() {
return Objects.hashCode(taskName, taskType);
}
}
private static class TaskTypeSelector implements ConfigSelector {
final String taskType;
TaskTypeSelector(String taskType) {
this.taskType = taskType;
}
@Nullable
@Override
public String codeBlockSelectorFor(Syntax syntax) {
return syntax.taskByTypeSelector(taskType);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TaskTypeSelector that = (TaskTypeSelector) o;
return Objects.equal(taskType, that.taskType);
}
@Override
public int hashCode() {
return taskType.hashCode();
}
}
private static class ConventionSelector implements ConfigSelector {
final String conventionName;
private ConventionSelector(String conventionName) {
this.conventionName = conventionName;
}
@Override
public String codeBlockSelectorFor(Syntax syntax) {
return syntax.conventionSelector(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConventionSelector that = (ConventionSelector) o;
return Objects.equal(conventionName, that.conventionName);
}
@Override
public int hashCode() {
return Objects.hashCode(conventionName);
}
}
/**
* Represents a statement in a script. Each statement has an optional comment that explains its purpose.
*/
private interface Statement {
enum Type {Empty, Single, Group}
@Nullable
String getComment();
/**
* Returns details of the size of this statement. Returns {@link Type#Empty} when this statement is empty and should not be included in the script.
*/
Type type();
/**
* Writes this statement to the given printer. Should not write the comment. Called only when {@link #type()} returns a value != {@link Type#Empty}
*/
void writeCodeTo(PrettyPrinter printer);
}
private static abstract class AbstractStatement implements Statement {
final String comment;
AbstractStatement(@Nullable String comment) {
this.comment = comment;
}
@Nullable
@Override
public String getComment() {
return comment;
}
@Override
public Type type() {
return Type.Single;
}
}
private static class MethodInvocation extends AbstractStatement {
final MethodInvocationExpression invocationExpression;
private MethodInvocation(String comment, MethodInvocationExpression invocationExpression) {
super(comment);
this.invocationExpression = invocationExpression;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(invocationExpression.with(printer.syntax));
}
}
private static class ContainerElement extends AbstractStatement implements ExpressionValue {
private final String comment;
private final String container;
private final String elementName;
@Nullable
private final String varName;
@Nullable
private final String elementType;
private final ScriptBlockImpl body = new ScriptBlockImpl();
public ContainerElement(String comment, String container, String elementName, @Nullable String elementType, @Nullable String varName) {
super(null);
this.comment = comment;
this.container = container;
this.elementName = elementName;
this.elementType = elementType;
this.varName = varName;
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
Statement statement = printer.syntax.createContainerElement(comment, container, elementName, elementType, varName, body.statements);
printer.printStatement(statement);
}
@Override
public String with(Syntax syntax) {
return syntax.referenceCreatedContainerElement(container, elementName, varName);
}
}
private static class PropertyAssignment extends AbstractStatement {
final String propertyName;
final ExpressionValue propertyValue;
final boolean legacyProperty;
private PropertyAssignment(String comment, String propertyName, ExpressionValue propertyValue, boolean legacyProperty) {
super(comment);
this.propertyName = propertyName;
this.propertyValue = propertyValue;
this.legacyProperty = legacyProperty;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.println(printer.syntax.propertyAssignment(this));
}
}
private static class SingleLineComment extends AbstractStatement {
private SingleLineComment(String comment) {
super(comment);
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
// NO OP
}
}
/**
* Represents the contents of a block.
*/
private interface BlockBody {
void writeBodyTo(PrettyPrinter printer);
List<Statement> getStatements();
}
private static class BlockStatement implements Statement {
private final String comment;
final String blockSelector;
final ScriptBlockImpl body = new ScriptBlockImpl();
BlockStatement(String blockSelector) {
this(null, blockSelector);
}
BlockStatement(@Nullable String comment, String blockSelector) {
this.comment = comment;
this.blockSelector = blockSelector;
}
@Nullable
@Override
public String getComment() {
return comment;
}
@Override
public Type type() {
return body.type();
}
void add(Statement statement) {
body.add(statement);
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.printBlock(blockSelector, body);
}
}
private static class ScriptBlock extends BlockStatement {
ScriptBlock(String comment, String blockSelector) {
super(comment, blockSelector);
}
@Override
public Type type() {
// Always treat as non-empty
return Type.Group;
}
}
private static class RepositoriesBlock extends BlockStatement implements RepositoriesBuilder {
private final BuildScriptBuilder builder;
RepositoriesBlock(final BuildScriptBuilder builder) {
super("repositories");
this.builder = builder;
}
@Override
public void mavenLocal(String comment) {
add(new MethodInvocation(comment, new MethodInvocationExpression("mavenLocal")));
}
@Override
public void mavenCentral(@Nullable String comment) {
add(new MethodInvocation(comment, new MethodInvocationExpression("mavenCentral")));
}
@Override
public void gradlePluginPortal(@Nullable String comment) {
add(new MethodInvocation(comment, new MethodInvocationExpression("gradlePluginPortal")));
}
@Override
public void maven(String comment, String url) {
add(new MavenRepoExpression(comment, url, builder));
}
}
private static class DependenciesBlock implements DependenciesBuilder, Statement, BlockBody {
final ListMultimap<String, Statement> dependencies = MultimapBuilder.linkedHashKeys().arrayListValues().build();
final ListMultimap<String, Statement> constraints = MultimapBuilder.linkedHashKeys().arrayListValues().build();
@Override
public void dependency(String configuration, @Nullable String comment, String... dependencies) {
this.dependencies.put(configuration, new DepSpec(configuration, comment, Arrays.asList(dependencies)));
}
@Override
public void dependencyConstraint(String configuration, @Nullable String comment, String... constraints) {
this.constraints.put(configuration, new DepSpec(configuration, comment, Arrays.asList(constraints)));
}
@Override
public void platformDependency(String configuration, @Nullable String comment, String dependency) {
this.dependencies.put(configuration, new PlatformDepSpec(configuration, comment, dependency));
}
@Override
public void projectDependency(String configuration, @Nullable String comment, String projectPath) {
this.dependencies.put(configuration, new ProjectDepSpec(configuration, comment, projectPath));
}
@Nullable
@Override
public String getComment() {
return null;
}
@Override
public Type type() {
return dependencies.isEmpty() && constraints.isEmpty() ? Type.Empty : Type.Group;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.printBlock("dependencies", this);
}
@Override
public void writeBodyTo(PrettyPrinter printer) {
if (!this.constraints.isEmpty()) {
ScriptBlockImpl constraintsBlock = new ScriptBlockImpl();
for (String config : this.constraints.keySet()) {
for (Statement constraintSpec : this.constraints.get(config)) {
constraintsBlock.add(constraintSpec);
}
}
printer.printBlock("constraints", constraintsBlock);
}
for (String config : dependencies.keySet()) {
for (Statement depSpec : dependencies.get(config)) {
printer.printStatement(depSpec);
}
}
}
@Override
public List<Statement> getStatements() {
List<Statement> statements = new ArrayList<>();
if (!constraints.isEmpty()) {
ScriptBlock constraintsBlock = new ScriptBlock(null, "constraints");
for (String config : constraints.keySet()) {
for(Statement statement : constraints.get(config)) {
constraintsBlock.add(statement);
}
}
statements.add(constraintsBlock);
}
for (String config : dependencies.keySet()) {
statements.addAll(dependencies.get(config));
}
return statements;
}
}
private static class MavenRepoExpression extends AbstractStatement {
private final String url;
private final BuildScriptBuilder builder;
MavenRepoExpression(@Nullable String comment, String url, BuildScriptBuilder builder) {
super(comment);
this.url = url;
this.builder = builder;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
ScriptBlockImpl statements = new ScriptBlockImpl();
ensureProtocolSecurity(url, statements);
printer.printBlock("maven", statements);
}
private void ensureProtocolSecurity(String url, ScriptBlockImpl statements) {
final URI uriAsURI = uriFromString(url);
if (GUtil.isSecureUrl(uriAsURI)) {
statements.propertyAssignment(null, "url", new MethodInvocationExpression(null, "uri", Collections.singletonList(new StringValue(url))), true);
} else {
LOGGER.warn("Repository URL: '{}' uses an insecure protocol.", url);
builder.insecureProtocolHandler.handle(uriAsURI, statements);
}
}
}
public static class ScriptBlockImpl implements ScriptBlockBuilder, BlockBody {
final List<Statement> statements = new ArrayList<>();
public void add(Statement statement) {
statements.add(statement);
}
@Override
public List<Statement> getStatements() {
return statements;
}
public Statement.Type type() {
for (Statement statement : statements) {
if (statement.type() != Statement.Type.Empty) {
return Statement.Type.Group;
}
}
return Statement.Type.Empty;
}
@Override
public void writeBodyTo(PrettyPrinter printer) {
printer.printStatements(statements);
}
@Override
public void propertyAssignment(String comment, String propertyName, Object propertyValue, boolean legacyProperty) {
statements.add(new PropertyAssignment(comment, propertyName, expressionValue(propertyValue), legacyProperty));
}
@Override
public void methodInvocation(String comment, String methodName, Object... methodArgs) {
statements.add(new MethodInvocation(comment, new MethodInvocationExpression(null, methodName, expressionValues(methodArgs))));
}
@Override
public void methodInvocation(@Nullable String comment, Expression target, String methodName, Object... methodArgs) {
statements.add(new MethodInvocation(comment, new MethodInvocationExpression(expressionValue(target), methodName, expressionValues(methodArgs))));
}
@Override
public ScriptBlockBuilder block(String comment, String methodName) {
ScriptBlock scriptBlock = new ScriptBlock(comment, methodName);
statements.add(scriptBlock);
return scriptBlock.body;
}
@Override
public void block(@Nullable String comment, String methodName, Action<? super ScriptBlockBuilder> blockContentsBuilder) {
blockContentsBuilder.execute(block(comment, methodName));
}
@Override
public Expression containerElement(@Nullable String comment, String container, String elementName, @Nullable String elementType, Action<? super ScriptBlockBuilder> blockContentsBuilder) {
ContainerElement containerElement = new ContainerElement(comment, container, elementName, elementType, null);
statements.add(containerElement);
blockContentsBuilder.execute(containerElement.body);
return containerElement;
}
@Override
public Expression propertyExpression(String value) {
return new LiteralValue(value);
}
@Override
public void comment(String comment) {
statements.add(new SingleLineComment(comment));
}
}
private static class TopLevelBlock extends ScriptBlockImpl {
final BlockStatement plugins = new BlockStatement("plugins");
final RepositoriesBlock repositories;
final DependenciesBlock dependencies = new DependenciesBlock();
final ConfigurationStatements<TaskTypeSelector> taskTypes = new ConfigurationStatements<>();
final ConfigurationStatements<TaskSelector> tasks = new ConfigurationStatements<>();
final ConfigurationStatements<ConventionSelector> conventions = new ConfigurationStatements<>();
private TopLevelBlock(BuildScriptBuilder builder) {
repositories = new RepositoriesBlock(builder);
}
@Override
public void writeBodyTo(PrettyPrinter printer) {
printer.printStatement(plugins);
printer.printStatement(repositories);
printer.printStatement(dependencies);
super.writeBodyTo(printer);
printer.printStatement(conventions);
printer.printStatement(taskTypes);
printer.printStatement(tasks);
}
public List<String> extractComments() {
List<String> comments = new ArrayList<>();
collectComments(plugins.body, comments);
collectComments(repositories.body, comments);
collectComments(dependencies, comments);
for (Statement otherBlock : getStatements()) {
if (otherBlock instanceof BlockStatement) {
collectComments(((BlockStatement) otherBlock).body, comments);
}
}
return comments;
}
private void collectComments(BlockBody body, List<String> comments) {
for (Statement statement : body.getStatements()) {
if (statement.getComment() != null) {
comments.add(statement.getComment());
}
}
}
}
private static class TaskRegistration implements Statement, ExpressionValue {
final String taskName;
final String taskType;
final String comment;
final ScriptBlockImpl body = new ScriptBlockImpl();
TaskRegistration(@Nullable String comment, String taskName, String taskType) {
this.comment = comment;
this.taskName = taskName;
this.taskType = taskType;
}
@Nullable
@Override
public String getComment() {
return comment;
}
@Override
public Type type() {
return Type.Group;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
printer.printBlock(printer.syntax.taskRegistration(taskName, taskType), body);
}
@Override
public boolean isBooleanType() {
return false;
}
@Override
public String with(Syntax syntax) {
return syntax.referenceRegisteredTask(taskName);
}
}
private static class ConfigurationStatements<T extends ConfigSelector> implements Statement {
final ListMultimap<T, Statement> blocks = MultimapBuilder.linkedHashKeys().arrayListValues().build();
void add(T selector, Statement statement) {
blocks.put(selector, statement);
}
@Nullable
@Override
public String getComment() {
return null;
}
@Override
public Type type() {
return blocks.isEmpty() ? Type.Empty : Type.Single;
}
@Override
public void writeCodeTo(PrettyPrinter printer) {
for (T configSelector : blocks.keySet()) {
String selector = configSelector.codeBlockSelectorFor(printer.syntax);
if (selector != null) {
BlockStatement statement = new BlockStatement(selector);
statement.body.statements.addAll(blocks.get(configSelector));
printer.printStatement(statement);
} else {
printer.printStatements(blocks.get(configSelector));
}
}
}
}
private static final class PrettyPrinter {
private final Syntax syntax;
private final PrintWriter writer;
private final boolean externalComments;
private String indent = "";
private String eolComment = null;
private int commentCount = 0;
private boolean needSeparatorLine = true;
private boolean firstStatementOfBlock = false;
private boolean hasSeparatorLine = false;
PrettyPrinter(Syntax syntax, PrintWriter writer, boolean externalComments) {
this.syntax = syntax;
this.writer = writer;
this.externalComments = externalComments;
}
public void printFileHeader(Collection<String> lines) {
if (externalComments) {
return;
}
println("/*");
println(" * This file was generated by the Gradle 'init' task.");
if (!lines.isEmpty()) {
println(" *");
for (String headerLine : lines) {
if (headerLine.isEmpty()) {
println(" *");
} else {
println(" * " + headerLine);
}
}
}
println(" */");
}
public void printBlock(String blockSelector, BlockBody blockBody) {
String indentBefore = indent;
println(blockSelector + " {");
indent = indent + " ";
needSeparatorLine = false;
firstStatementOfBlock = true;
blockBody.writeBodyTo(this);
indent = indentBefore;
println("}");
// Write a line separator after any block
needSeparatorLine = true;
}
public void printStatements(List<? extends Statement> statements) {
for (Statement statement : statements) {
printStatement(statement);
}
}
private void printStatementSeparator() {
if (needSeparatorLine && !hasSeparatorLine) {
println();
needSeparatorLine = false;
}
}
private void printStatement(Statement statement) {
Statement.Type type = statement.type();
if (type == Statement.Type.Empty) {
return;
}
boolean hasComment = statement.getComment() != null;
// Add separators before and after anything with a comment or that is a block or group of statements
boolean needsSeparator = hasComment || type == Statement.Type.Group;
if (needsSeparator && !firstStatementOfBlock) {
needSeparatorLine = true;
}
printStatementSeparator();
if (hasComment) {
if (externalComments) {
commentCount++;
eolComment = " // <" + commentCount + ">";
} else {
for (String line : splitComment(statement.getComment())) {
println("// " + line);
}
}
}
statement.writeCodeTo(this);
firstStatementOfBlock = false;
if (needsSeparator) {
needSeparatorLine = true;
}
}
private void println(String s) {
if (!indent.isEmpty()) {
writer.print(indent);
}
if (eolComment != null) {
writer.println(s + eolComment);
eolComment = null;
} else {
writer.println(s);
}
hasSeparatorLine = false;
}
private void println() {
writer.println();
hasSeparatorLine = true;
}
}
private interface Syntax {
String pluginDependencySpec(String pluginId, @Nullable String version);
String nestedPluginDependencySpec(String pluginId, @Nullable String version);
String dependencySpec(String config, String notation);
String propertyAssignment(PropertyAssignment expression);
@Nullable
String conventionSelector(ConventionSelector selector);
String taskSelector(TaskSelector selector);
String taskByTypeSelector(String taskType);
String string(String string);
String taskRegistration(String taskName, String taskType);
String referenceRegisteredTask(String taskName);
String mapLiteral(Map<String, ExpressionValue> map);
String firstArg(ExpressionValue argument);
Statement createContainerElement(@Nullable String comment, String container, String elementName, @Nullable String elementType, @Nullable String varName, List<Statement> body);
String referenceCreatedContainerElement(String container, String elementName, @Nullable String varName);
String containerElement(String container, String element);
void configureConventionPlugin(@Nullable String comment, BlockStatement plugins, RepositoriesBlock repositories);
}
private static final class KotlinSyntax implements Syntax {
@Override
public String string(String string) {
return '"' + string + '"';
}
@Override
public String mapLiteral(Map<String, ExpressionValue> map) {
StringBuilder builder = new StringBuilder();
builder.append("mapOf(");
boolean first = true;
for (Map.Entry<String, ExpressionValue> entry : map.entrySet()) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(string(entry.getKey()));
builder.append(" to ");
builder.append(entry.getValue().with(this));
}
builder.append(")");
return builder.toString();
}
@Override
public String firstArg(ExpressionValue argument) {
return argument.with(this);
}
@Override
public String pluginDependencySpec(String pluginId, @Nullable String version) {
if (version != null) {
return "id(\"" + pluginId + "\") version \"" + version + "\"";
} else if (pluginId.contains(".")) {
return "id(\"" + pluginId + "\")";
}
return pluginId.matches("[a-z]+") ? pluginId : "`" + pluginId + "`";
}
@Override
public String nestedPluginDependencySpec(String pluginId, @Nullable String version) {
if (version != null) {
throw new UnsupportedOperationException();
}
return "plugins.apply(\"" + pluginId + "\")";
}
@Override
public String dependencySpec(String config, String notation) {
return config + "(" + notation + ")";
}
@Override
public String propertyAssignment(PropertyAssignment expression) {
String propertyName = expression.propertyName;
ExpressionValue propertyValue = expression.propertyValue;
if (expression.legacyProperty) {
if (propertyValue.isBooleanType()) {
return booleanPropertyNameFor(propertyName) + " = " + propertyValue.with(this);
}
return propertyName + " = " + propertyValue.with(this);
} else {
return propertyName + ".set(" + propertyValue.with(this) + ")";
}
}
// In Kotlin:
//
// > Boolean accessor methods (where the name of the getter starts with is and the name of
// > the setter starts with set) are represented as properties which have the same name as
// > the getter method. Boolean properties are visible with a `is` prefix in Kotlin
//
// https://kotlinlang.org/docs/reference/java-interop.html#getters-and-setters
//
// This code assumes all configurable Boolean property getters follow the `is` prefix convention.
//
private String booleanPropertyNameFor(String propertyName) {
return "is" + StringUtils.capitalize(propertyName);
}
@Override
public String conventionSelector(ConventionSelector selector) {
return selector.conventionName;
}
@Override
public String taskSelector(TaskSelector selector) {
return "tasks." + selector.taskName;
}
@Override
public String taskByTypeSelector(String taskType) {
return "tasks.withType<" + taskType + ">()";
}
@Override
public String taskRegistration(String taskName, String taskType) {
return "val " + taskName + " by tasks.registering(" + taskType + "::class)";
}
@Override
public String referenceRegisteredTask(String taskName) {
return taskName;
}
@Override
public Statement createContainerElement(String comment, String container, String elementName, @Nullable String elementType, String varName, List<Statement> body) {
String literal;
if (varName == null) {
if (elementType == null) {
literal = "val " + elementName + " by " + container + ".creating";
} else {
literal = container + ".create<" + elementType + ">(" + string(elementName) + ")";
}
} else {
if (elementType == null) {
literal = "val " + varName + " = " + container + ".create(" + string(elementName) + ")";
} else {
literal = "val " + varName + " = " + container + ".create<" + elementType + ">(" + string(elementName) + ")";
}
}
BlockStatement blockStatement = new ScriptBlock(comment, literal);
for (Statement statement : body) {
blockStatement.add(statement);
}
return blockStatement;
}
@Override
public String referenceCreatedContainerElement(String container, String elementName, String varName) {
if (varName == null) {
return elementName;
} else {
return varName;
}
}
@Override
public String containerElement(String container, String element) {
return container + "[" + string(element) + "]";
}
@Override
public void configureConventionPlugin(@Nullable String comment, BlockStatement plugins, RepositoriesBlock repositories) {
plugins.add(new PluginSpec("kotlin-dsl", null, comment));
}
}
private static final class GroovySyntax implements Syntax {
@Override
public String string(String string) {
return "'" + string + "'";
}
@Override
public String mapLiteral(Map<String, ExpressionValue> map) {
StringBuilder builder = new StringBuilder();
builder.append("[");
addEntries(map, builder);
builder.append("]");
return builder.toString();
}
private void addEntries(Map<String, ExpressionValue> map, StringBuilder builder) {
boolean first = true;
for (Map.Entry<String, ExpressionValue> entry : map.entrySet()) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(entry.getKey());
builder.append(": ");
builder.append(entry.getValue().with(this));
}
}
@Override
public String firstArg(ExpressionValue argument) {
if (argument instanceof MapLiteralValue) {
MapLiteralValue literalValue = (MapLiteralValue) argument;
StringBuilder builder = new StringBuilder();
addEntries(literalValue.literal, builder);
return builder.toString();
} else {
return argument.with(this);
}
}
@Override
public String pluginDependencySpec(String pluginId, @Nullable String version) {
if (version != null) {
return "id '" + pluginId + "' version '" + version + "'";
}
return "id '" + pluginId + "'";
}
@Override
public String nestedPluginDependencySpec(String pluginId, @Nullable String version) {
if (version != null) {
throw new UnsupportedOperationException();
}
return "apply plugin: '" + pluginId + "'";
}
@Override
public String dependencySpec(String config, String notation) {
return config + " " + notation;
}
@Override
public String propertyAssignment(PropertyAssignment expression) {
String propertyName = expression.propertyName;
ExpressionValue propertyValue = expression.propertyValue;
return propertyName + " = " + propertyValue.with(this);
}
@Override
public String conventionSelector(ConventionSelector selector) {
return null;
}
@Override
public String taskSelector(TaskSelector selector) {
return "tasks.named('" + selector.taskName + "')";
}
@Override
public String taskByTypeSelector(String taskType) {
return "tasks.withType(" + taskType + ")";
}
@Override
public String taskRegistration(String taskName, String taskType) {
return "tasks.register('" + taskName + "', " + taskType + ")";
}
@Override
public String referenceRegisteredTask(String taskName) {
return "tasks." + taskName;
}
@Override
public Statement createContainerElement(String comment, String container, String elementName, @Nullable String elementType, String varName, List<Statement> body) {
ScriptBlock outerBlock = new ScriptBlock(comment, container);
ScriptBlock innerBlock = new ScriptBlock(null, elementType == null ? elementName : elementName + "(" + elementType + ")");
outerBlock.add(innerBlock);
for (Statement statement : body) {
innerBlock.add(statement);
}
return outerBlock;
}
@Override
public String referenceCreatedContainerElement(String container, String elementName, String varName) {
return container + "." + elementName;
}
@Override
public String containerElement(String container, String element) {
return container + "." + element;
}
@Override
public void configureConventionPlugin(@Nullable String comment, BlockStatement plugins, RepositoriesBlock repositories) {
plugins.add(new PluginSpec("groovy-gradle-plugin", null, comment));
}
}
public interface InsecureProtocolHandler {
void handle(URI uri, BuildScriptBuilder.ScriptBlockImpl statements);
static InsecureProtocolHandler forOption(InsecureProtocolOption insecureProtocolOption, BuildInitDsl dsl, DocumentationRegistry documentationRegistry) {
switch (insecureProtocolOption) {
case FAIL:
return new BuildScriptBuilder.FailingHandler(documentationRegistry);
case WARN:
return new BuildScriptBuilder.WarningHandler(dsl, documentationRegistry);
case ALLOW:
return new BuildScriptBuilder.AllowingHandler();
case UPGRADE:
return new BuildScriptBuilder.UpgradingHandler();
default:
throw new IllegalStateException(String.format("Unknown handler: '%s'.", insecureProtocolOption));
}
}
}
public static class FailingHandler implements InsecureProtocolHandler {
private final DocumentationRegistry documentationRegistry;
public FailingHandler(DocumentationRegistry documentationRegistry) {
this.documentationRegistry = documentationRegistry;
}
@Override
public void handle(URI uri, ScriptBlockImpl statements) {
LOGGER.error("Gradle found an insecure protocol in a repository definition. The current strategy for handling insecure URLs is to fail. For more options, see {}.", documentationRegistry.getDocumentationFor("build_init_plugin", "allow_insecure"));
throw new GradleException(String.format("Build aborted due to insecure protocol in repository: %s", uri));
}
}
public static class WarningHandler implements InsecureProtocolHandler {
private final BuildInitDsl dsl;
private final DocumentationRegistry documentationRegistry;
public WarningHandler(BuildInitDsl dsl, DocumentationRegistry documentationRegistry) {
this.dsl = dsl;
this.documentationRegistry = documentationRegistry;
}
@Override
public void handle(URI uri, BuildScriptBuilder.ScriptBlockImpl statements) {
LOGGER.warn("Gradle found an insecure protocol in a repository definition. You will have to opt into allowing insecure protocols in the generated build file. See {}.", documentationRegistry.getDocumentationFor("build_init_plugin", "allow_insecure"));
statements.propertyAssignment(null, "url", new BuildScriptBuilder.MethodInvocationExpression(null, "uri", Collections.singletonList(new BuildScriptBuilder.StringValue(uri.toString()))), true);
statements.comment(buildAllowInsecureProtocolComment(dsl));
}
private String buildAllowInsecureProtocolComment(BuildInitDsl dsl) {
final PropertyAssignment assignment = new PropertyAssignment(null, "allowInsecureProtocol", new BuildScriptBuilder.LiteralValue(true), true);
final StringWriter result = new StringWriter();
try (PrintWriter writer = new PrintWriter(result)) {
PrettyPrinter printer = new PrettyPrinter(syntaxFor(dsl), writer, false);
assignment.writeCodeTo(printer);
return result.toString();
} catch (Exception e) {
throw new GradleException("Could not write comment.", e);
}
}
}
public static class UpgradingHandler implements InsecureProtocolHandler {
@Override
public void handle(URI uri, BuildScriptBuilder.ScriptBlockImpl statements) {
final URI secureUri;
try {
secureUri = GUtil.toSecureUrl(uri);
} catch (final IllegalArgumentException e) {
throw new GradleException(String.format("Can't upgrade insecure protocol for URL: '%s' as no replacement protocol exists.", uri));
}
LOGGER.warn("Upgrading protocol to '{}'.", secureUri);
statements.propertyAssignment(null, "url", new BuildScriptBuilder.MethodInvocationExpression(null, "uri", Collections.singletonList(new BuildScriptBuilder.StringValue(secureUri.toString()))), true);
}
}
public static class AllowingHandler implements InsecureProtocolHandler {
@Override
public void handle(URI uri, BuildScriptBuilder.ScriptBlockImpl statements) {
statements.propertyAssignment(null, "url", new BuildScriptBuilder.MethodInvocationExpression(null, "uri", Collections.singletonList(new BuildScriptBuilder.StringValue(uri.toString()))), true);
statements.propertyAssignment(null, "allowInsecureProtocol", new BuildScriptBuilder.LiteralValue(true), true);
}
}
}
| Refactor InsecureProtocolHandler class to MavenRepositoryURLHandler, encapsulate all Maven repo URL handling, not just insecure ones.
| subprojects/build-init/src/main/java/org/gradle/buildinit/plugins/internal/BuildScriptBuilder.java | Refactor InsecureProtocolHandler class to MavenRepositoryURLHandler, encapsulate all Maven repo URL handling, not just insecure ones. |
|
Java | apache-2.0 | e7fc7ca8c1050c9668a69547f0073f02e1b0e70f | 0 | rwl/requestfactory-addon | package org.springframework.roo.addon.jpa;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.springframework.roo.addon.propfiles.PropFileOperations;
import org.springframework.roo.file.monitor.event.FileDetails;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.process.manager.FileManager;
import org.springframework.roo.process.manager.MutableFile;
import org.springframework.roo.project.Dependency;
import org.springframework.roo.project.Filter;
import org.springframework.roo.project.Path;
import org.springframework.roo.project.PathResolver;
import org.springframework.roo.project.Plugin;
import org.springframework.roo.project.ProjectMetadata;
import org.springframework.roo.project.ProjectOperations;
import org.springframework.roo.project.Property;
import org.springframework.roo.project.Repository;
import org.springframework.roo.project.Resource;
import org.springframework.roo.support.logging.HandlerUtils;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.FileCopyUtils;
import org.springframework.roo.support.util.StringUtils;
import org.springframework.roo.support.util.TemplateUtils;
import org.springframework.roo.support.util.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Provides JPA configuration operations.
*
* @author Stefan Schmidt
* @author Alan Stewart
* @since 1.0
*/
@Component
@Service
public class JpaOperationsImpl implements JpaOperations {
private static final Logger logger = HandlerUtils.getLogger(JpaOperationsImpl.class);
private static final String PERSISTENCE_UNIT = "persistence-unit";
private static final String GAE_PERSISTENCE_UNIT_NAME = "transactions-optional";
private static final String PERSISTENCE_UNIT_NAME = "persistenceUnit";
@Reference private FileManager fileManager;
@Reference private PathResolver pathResolver;
@Reference private MetadataService metadataService;
@Reference private ProjectOperations projectOperations;
@Reference private PropFileOperations propFileOperations;
public boolean isJpaInstallationPossible() {
return metadataService.get(ProjectMetadata.getProjectIdentifier()) != null && !fileManager.exists(pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml"));
}
public boolean isJpaInstalled() {
return metadataService.get(ProjectMetadata.getProjectIdentifier()) != null && fileManager.exists(pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml"));
}
public boolean hasDatabaseProperties() {
return fileManager.exists(getDatabasePropertiesPath());
}
public SortedSet<String> getDatabaseProperties() {
if (fileManager.exists(getDatabasePropertiesPath())) {
return propFileOperations.getPropertyKeys(Path.SPRING_CONFIG_ROOT, "database.properties", true);
} else {
return getPropertiesFromDataNucleusConfiguration();
}
}
private String getDatabasePropertiesPath() {
return pathResolver.getIdentifier(Path.SPRING_CONFIG_ROOT, "database.properties");
}
public void configureJpa(OrmProvider ormProvider, JdbcDatabase database, String jndi, String applicationId, String hostName, String databaseName, String userName, String password, String persistenceUnit) {
Assert.notNull(ormProvider, "ORM provider required");
Assert.notNull(database, "JDBC database required");
// Parse the configuration.xml file
Element configuration = XmlUtils.getConfiguration(getClass());
// Remove unnecessary artifacts not specific to current database and JPA provider
cleanup(configuration, ormProvider, database);
updateApplicationContext(ormProvider, database, jndi, persistenceUnit);
updatePersistenceXml(ormProvider, database, databaseName, userName, password, persistenceUnit);
updateGaeXml(ormProvider, database, applicationId);
updateVMforceConfigProperties(ormProvider, database, userName, password);
if (!StringUtils.hasText(jndi)) {
updateDatabaseProperties(ormProvider, database, hostName, databaseName, userName, password);
}
updateLog4j(ormProvider);
updatePomProperties(configuration, ormProvider, database);
updateDependencies(configuration, ormProvider, database);
updateRepositories(configuration, ormProvider, database);
updatePluginRepositories(configuration, ormProvider, database);
updateFilters(configuration, ormProvider, database);
updateResources(configuration, ormProvider, database);
updateBuildPlugins(configuration, ormProvider, database);
}
private void updateApplicationContext(OrmProvider ormProvider, JdbcDatabase database, String jndi, String persistenceUnit) {
String contextPath = pathResolver.getIdentifier(Path.SPRING_CONFIG_ROOT, "applicationContext.xml");
MutableFile contextMutableFile = null;
Document appCtx;
try {
if (fileManager.exists(contextPath)) {
contextMutableFile = fileManager.updateFile(contextPath);
appCtx = XmlUtils.getDocumentBuilder().parse(contextMutableFile.getInputStream());
} else {
throw new IllegalStateException("Could not acquire applicationContext.xml in " + contextPath);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = appCtx.getDocumentElement();
// Checking for existence of configurations, if found abort
Element dataSource = XmlUtils.findFirstElement("/beans/bean[@id = 'dataSource']", root);
Element dataSourceJndi = XmlUtils.findFirstElement("/beans/jndi-lookup[@id = 'dataSource']", root);
if (ormProvider == OrmProvider.DATANUCLEUS || ormProvider == OrmProvider.DATANUCLEUS_2) {
if (dataSource != null) {
root.removeChild(dataSource);
}
if (dataSourceJndi != null) {
root.removeChild(dataSourceJndi);
}
} else if (!StringUtils.hasText(jndi) && dataSource == null) {
dataSource = appCtx.createElement("bean");
dataSource.setAttribute("class", "org.apache.commons.dbcp.BasicDataSource");
dataSource.setAttribute("destroy-method", "close");
dataSource.setAttribute("id", "dataSource");
dataSource.appendChild(createPropertyElement("driverClassName", "${database.driverClassName}", appCtx));
dataSource.appendChild(createPropertyElement("url", "${database.url}", appCtx));
dataSource.appendChild(createPropertyElement("username", "${database.username}", appCtx));
dataSource.appendChild(createPropertyElement("password", "${database.password}", appCtx));
root.appendChild(dataSource);
if (dataSourceJndi != null) {
dataSourceJndi.getParentNode().removeChild(dataSourceJndi);
}
} else if (StringUtils.hasText(jndi)) {
if (dataSourceJndi == null) {
dataSourceJndi = appCtx.createElement("jee:jndi-lookup");
dataSourceJndi.setAttribute("id", "dataSource");
root.appendChild(dataSourceJndi);
}
dataSourceJndi.setAttribute("jndi-name", jndi);
if (dataSource != null) {
dataSource.getParentNode().removeChild(dataSource);
}
}
if (dataSource != null) {
Element validationQueryElement = XmlUtils.findFirstElement("property[@name = 'validationQuery']", dataSource);
Element testOnBorrowElement = XmlUtils.findFirstElement("property[@name = 'testOnBorrow']", dataSource);
if (database != JdbcDatabase.MYSQL && validationQueryElement != null && testOnBorrowElement != null) {
dataSource.removeChild(validationQueryElement);
dataSource.removeChild(testOnBorrowElement);
} else if (database == JdbcDatabase.MYSQL && validationQueryElement == null && testOnBorrowElement == null) {
dataSource.appendChild(createPropertyElement("validationQuery", "SELECT 1 FROM DUAL", appCtx));
dataSource.appendChild(createPropertyElement("testOnBorrow", "true", appCtx));
}
}
Element transactionManager = XmlUtils.findFirstElement("/beans/bean[@id = 'transactionManager']", root);
if (transactionManager == null) {
transactionManager = appCtx.createElement("bean");
transactionManager.setAttribute("id", "transactionManager");
transactionManager.setAttribute("class", "org.springframework.orm.jpa.JpaTransactionManager");
transactionManager.appendChild(createRefElement("entityManagerFactory", "entityManagerFactory", appCtx));
root.appendChild(transactionManager);
}
Element aspectJTxManager = XmlUtils.findFirstElement("/beans/annotation-driven", root);
if (aspectJTxManager == null) {
aspectJTxManager = appCtx.createElement("tx:annotation-driven");
aspectJTxManager.setAttribute("mode", "aspectj");
aspectJTxManager.setAttribute("transaction-manager", "transactionManager");
root.appendChild(aspectJTxManager);
}
Element entityManagerFactory = XmlUtils.findFirstElement("/beans/bean[@id = 'entityManagerFactory']", root);
if (entityManagerFactory != null) {
root.removeChild(entityManagerFactory);
}
entityManagerFactory = appCtx.createElement("bean");
entityManagerFactory.setAttribute("id", "entityManagerFactory");
switch (database) {
case GOOGLE_APP_ENGINE:
entityManagerFactory.setAttribute("class", "org.springframework.orm.jpa.LocalEntityManagerFactoryBean");
entityManagerFactory.appendChild(createPropertyElement("persistenceUnitName", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : GAE_PERSISTENCE_UNIT_NAME), appCtx));
break;
default:
entityManagerFactory.setAttribute("class", "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean");
switch (ormProvider) {
case DATANUCLEUS:
case DATANUCLEUS_2:
entityManagerFactory.appendChild(createPropertyElement("persistenceUnitName", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : PERSISTENCE_UNIT_NAME), appCtx));
break;
default:
entityManagerFactory.appendChild(createRefElement("dataSource", "dataSource", appCtx));
break;
}
break;
}
root.appendChild(entityManagerFactory);
XmlUtils.removeTextNodes(root);
XmlUtils.writeXml(contextMutableFile.getOutputStream(), appCtx);
}
private void updatePersistenceXml(OrmProvider ormProvider, JdbcDatabase database, String databaseName, String userName, String password, String persistenceUnit) {
String persistencePath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
MutableFile persistenceMutableFile = null;
Document persistence;
try {
if (fileManager.exists(persistencePath)) {
persistenceMutableFile = fileManager.updateFile(persistencePath);
persistence = XmlUtils.getDocumentBuilder().parse(persistenceMutableFile.getInputStream());
} else {
persistenceMutableFile = fileManager.createFile(persistencePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "persistence-template.xml");
Assert.notNull(templateInputStream, "Could not acquire peristence.xml template");
persistence = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Properties dialects = new Properties();
try {
InputStream dialectsInputStream = TemplateUtils.getTemplate(getClass(), "jpa-dialects.properties");
Assert.notNull(dialectsInputStream, "Could not acquire jpa-dialects.properties");
dialects.load(dialectsInputStream);
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = persistence.getDocumentElement();
Element persistenceElement = XmlUtils.findFirstElement("/persistence", root);
Assert.notNull(persistenceElement, "No persistence element found");
Element persistenceUnitElement;
if (StringUtils.hasText(persistenceUnit)) {
persistenceUnitElement = XmlUtils.findFirstElement(PERSISTENCE_UNIT + "[@name = '" + persistenceUnit + "']", persistenceElement);
} else {
persistenceUnitElement = XmlUtils.findFirstElement(PERSISTENCE_UNIT + "[@name = '" + (database == JdbcDatabase.GOOGLE_APP_ENGINE ? GAE_PERSISTENCE_UNIT_NAME : PERSISTENCE_UNIT_NAME) + "']", persistenceElement);
}
if (persistenceUnitElement != null) {
while (persistenceUnitElement.getFirstChild() != null) {
persistenceUnitElement.removeChild(persistenceUnitElement.getFirstChild());
}
} else {
persistenceUnitElement = persistence.createElement(PERSISTENCE_UNIT);
persistenceElement.appendChild(persistenceUnitElement);
}
// Set attributes for DataNuclueus 1.1.x/GAE-specific requirements
switch (ormProvider) {
case DATANUCLEUS:
persistenceElement.setAttribute("version", "1.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd");
break;
default:
persistenceElement.setAttribute("version", "2.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
break;
}
// Add provider element
Element provider = persistence.createElement("provider");
switch (database) {
case GOOGLE_APP_ENGINE:
persistenceUnitElement.setAttribute("name", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : GAE_PERSISTENCE_UNIT_NAME));
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAlternateAdapter());
break;
case VMFORCE:
persistenceUnitElement.setAttribute("name", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : PERSISTENCE_UNIT_NAME));
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAdapter());
break;
default:
persistenceUnitElement.setAttribute("name", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : PERSISTENCE_UNIT_NAME));
persistenceUnitElement.setAttribute("transaction-type", "RESOURCE_LOCAL");
provider.setTextContent(ormProvider.getAdapter());
break;
}
persistenceUnitElement.appendChild(provider);
// Add properties
Element properties = persistence.createElement("properties");
switch (ormProvider) {
case HIBERNATE:
properties.appendChild(createPropertyElement("hibernate.dialect", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment(" value=\"create\" to build a new database on each run; value=\"update\" to modify an existing database; value=\"create-drop\" means the same as \"create\" but also drops tables when Hibernate closes; value=\"validate\" makes no changes to the database ")); // ROO-627
String hbm2dll = "create";
if (database == JdbcDatabase.DB2400) {
hbm2dll = "validate";
}
properties.appendChild(createPropertyElement("hibernate.hbm2ddl.auto", hbm2dll, persistence));
properties.appendChild(createPropertyElement("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy", persistence));
properties.appendChild(createPropertyElement("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy", persistence));
properties.appendChild(persistence.createComment(" Uncomment the following two properties for JBoss only "));
properties.appendChild(persistence.createComment(" property name=\"hibernate.validator.apply_to_ddl\" value=\"false\" /"));
properties.appendChild(persistence.createComment(" property name=\"hibernate.validator.autoregister_listeners\" value=\"false\" /"));
break;
case OPENJPA:
properties.appendChild(createPropertyElement("openjpa.jdbc.DBDictionary", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment(" value=\"buildSchema\" to runtime forward map the DDL SQL; value=\"validate\" makes no changes to the database ")); // ROO-627
properties.appendChild(createPropertyElement("openjpa.jdbc.SynchronizeMappings", "buildSchema", persistence));
properties.appendChild(createPropertyElement("openjpa.RuntimeUnenhancedClasses", "supported", persistence));
break;
case ECLIPSELINK:
properties.appendChild(createPropertyElement("eclipselink.target-database", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment(" value=\"drop-and-create-tables\" to build a new database on each run; value=\"create-tables\" creates new tables if needed; value=\"none\" makes no changes to the database ")); // ROO-627
properties.appendChild(createPropertyElement("eclipselink.ddl-generation", "drop-and-create-tables", persistence));
properties.appendChild(createPropertyElement("eclipselink.ddl-generation.output-mode", "database", persistence));
properties.appendChild(createPropertyElement("eclipselink.weaving", "static", persistence));
break;
case DATANUCLEUS:
case DATANUCLEUS_2:
String connectionString = database.getConnectionString();
switch (database) {
case GOOGLE_APP_ENGINE:
properties.appendChild(createPropertyElement("datanucleus.NontransactionalRead", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.NontransactionalWrite", "true", persistence));
break;
case VMFORCE:
userName = "${sfdc.userName}";
password = "${sfdc.password}";
properties.appendChild(createPropertyElement("datanucleus.Optimistic", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.datastoreTransactionDelayOperations", "true", persistence));
properties.appendChild(createPropertyElement("sfdcConnectionName", "DefaultSFDCConnection", persistence));
break;
default:
properties.appendChild(createPropertyElement("datanucleus.ConnectionDriverName", database.getDriverClassName(), persistence));
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
connectionString = connectionString.replace("TO_BE_CHANGED_BY_ADDON", projectMetadata.getProjectName());
switch (database) {
case HYPERSONIC_IN_MEMORY:
case HYPERSONIC_PERSISTENT:
case H2_IN_MEMORY:
userName = StringUtils.hasText(userName) ? userName : "sa";
break;
case DERBY:
break;
default:
logger.warning("Please enter your database details in src/main/resources/META-INF/persistence.xml.");
break;
}
properties.appendChild(createPropertyElement("datanucleus.storeManagerType", "rdbms", persistence));
}
properties.appendChild(createPropertyElement("datanucleus.ConnectionURL", connectionString, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionUserName", userName, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionPassword", password, persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateSchema", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateTables", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateColumns", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateTables", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.jpa.addClassTransformer", "false", persistence));
break;
}
persistenceUnitElement.appendChild(properties);
XmlUtils.writeXml(persistenceMutableFile.getOutputStream(), persistence);
}
private void updateGaeXml(OrmProvider ormProvider, JdbcDatabase database, String applicationId) {
String appenginePath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/appengine-web.xml");
boolean appenginePathExists = fileManager.exists(appenginePath);
String loggingPropertiesPath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/logging.properties");
boolean loggingPropertiesPathExists = fileManager.exists(loggingPropertiesPath);
if (database != JdbcDatabase.GOOGLE_APP_ENGINE) {
if (appenginePathExists) {
fileManager.delete(appenginePath);
}
if (loggingPropertiesPathExists) {
fileManager.delete(loggingPropertiesPath);
}
return;
} else {
MutableFile appengineMutableFile = null;
Document appengine;
try {
if (appenginePathExists) {
appengineMutableFile = fileManager.updateFile(appenginePath);
appengine = XmlUtils.getDocumentBuilder().parse(appengineMutableFile.getInputStream());
} else {
appengineMutableFile = fileManager.createFile(appenginePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "appengine-web-template.xml");
Assert.notNull(templateInputStream, "Could not acquire appengine-web.xml template");
appengine = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element rootElement = appengine.getDocumentElement();
Element applicationElement = XmlUtils.findFirstElement("/appengine-web-app/application", rootElement);
applicationElement.setTextContent(StringUtils.hasText(applicationId) ? applicationId : getProjectName());
XmlUtils.writeXml(appengineMutableFile.getOutputStream(), appengine);
if (!loggingPropertiesPathExists) {
try {
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "logging.properties");
FileCopyUtils.copy(templateInputStream, fileManager.createFile(loggingPropertiesPath).getOutputStream());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
}
private void updateDatabaseProperties(OrmProvider ormProvider, JdbcDatabase database, String hostName, String databaseName, String userName, String password) {
String databasePath = getDatabasePropertiesPath();
boolean databaseExists = fileManager.exists(databasePath);
if (ormProvider == OrmProvider.DATANUCLEUS || ormProvider == OrmProvider.DATANUCLEUS_2) {
if (databaseExists) {
fileManager.delete(databasePath);
}
return;
}
MutableFile databaseMutableFile = null;
Properties props = new Properties();
try {
if (databaseExists) {
databaseMutableFile = fileManager.updateFile(databasePath);
props.load(databaseMutableFile.getInputStream());
} else {
databaseMutableFile = fileManager.createFile(databasePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "database-template.properties");
Assert.notNull(templateInputStream, "Could not acquire database properties template");
props.load(templateInputStream);
}
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
props.put("database.driverClassName", database.getDriverClassName());
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
String connectionString = database.getConnectionString();
connectionString = connectionString.replace("TO_BE_CHANGED_BY_ADDON", projectMetadata.getProjectName());
if (StringUtils.hasText(databaseName)) {
// Oracle uses a different connection URL - see ROO-1203
String dbDelimiter = database == JdbcDatabase.ORACLE ? ":" : "/";
connectionString += databaseName.startsWith(dbDelimiter) ? databaseName : dbDelimiter + databaseName;
}
if (!StringUtils.hasText(hostName)) {
hostName = "localhost";
}
connectionString = connectionString.replace("HOST_NAME", hostName);
props.put("database.url", connectionString);
String dbPropsMsg = "Please enter your database details in src/main/resources/META-INF/spring/database.properties.";
switch (database) {
case HYPERSONIC_IN_MEMORY:
case HYPERSONIC_PERSISTENT:
case H2_IN_MEMORY:
userName = StringUtils.hasText(userName) ? userName : "sa";
break;
case DERBY:
break;
case SYBASE:
userName = StringUtils.hasText(userName) ? userName : "sa";
logger.warning(dbPropsMsg);
break;
default:
logger.warning(dbPropsMsg);
break;
}
props.put("database.username", StringUtils.trimToEmpty(userName));
props.put("database.password", StringUtils.trimToEmpty(password));
try {
props.store(databaseMutableFile.getOutputStream(), "Updated at " + new Date());
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void updateVMforceConfigProperties(OrmProvider ormProvider, JdbcDatabase database, String userName, String password) {
String configPath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "config.properties");
boolean configExists = fileManager.exists(configPath);
if (database != JdbcDatabase.VMFORCE) {
if (configExists) {
fileManager.delete(configPath);
}
return;
}
MutableFile configMutableFile = null;
Properties props = new Properties();
try {
if (configExists) {
configMutableFile = fileManager.updateFile(configPath);
props.load(configMutableFile.getInputStream());
} else {
configMutableFile = fileManager.createFile(configPath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "config-template.properties");
Assert.notNull(templateInputStream, "Could not acquire config properties template");
props.load(templateInputStream);
}
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
props.put("sfdc.userName", StringUtils.trimToEmpty(userName));
props.put("sfdc.password", StringUtils.trimToEmpty(password));
try {
props.store(configMutableFile.getOutputStream(), "Updated at " + new Date());
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void updateLog4j(OrmProvider ormProvider) {
try {
String log4jPath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "log4j.properties");
if (fileManager.exists(log4jPath)) {
MutableFile log4jMutableFile = fileManager.updateFile(log4jPath);
Properties props = new Properties();
props.load(log4jMutableFile.getInputStream());
final String dnKey = "log4j.category.DataNucleus";
if (ormProvider == OrmProvider.DATANUCLEUS && !props.containsKey(dnKey)) {
props.put(dnKey, "WARN");
props.store(log4jMutableFile.getOutputStream(), "Updated at " + new Date());
} else if (ormProvider != OrmProvider.DATANUCLEUS && props.containsKey(dnKey)) {
props.remove(dnKey);
props.store(log4jMutableFile.getOutputStream(), "Updated at " + new Date());
}
}
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void updatePomProperties(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseProperties = XmlUtils.findElements(getDbXPath(database) + "/properties/*", configuration);
for (Element property : databaseProperties) {
projectOperations.addProperty(new Property(property));
}
List<Element> providerProperties = XmlUtils.findElements(getProviderXPath(ormProvider) + "/properties/*", configuration);
for (Element property : providerProperties) {
projectOperations.addProperty(new Property(property));
}
}
private void updateDependencies(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseDependencies = XmlUtils.findElements(getDbXPath(database) + "/dependencies/dependency", configuration);
for (Element dependencyElement : databaseDependencies) {
projectOperations.addDependency(new Dependency(dependencyElement));
}
List<Element> ormDependencies = XmlUtils.findElements(getProviderXPath(ormProvider) + "/dependencies/dependency", configuration);
for (Element dependencyElement : ormDependencies) {
projectOperations.addDependency(new Dependency(dependencyElement));
}
// Hard coded to JPA & Hibernate Validator for now
List<Element> jpaDependencies = XmlUtils.findElements("/configuration/persistence/provider[@id = 'JPA']/dependencies/dependency", configuration);
for (Element dependencyElement : jpaDependencies) {
projectOperations.addDependency(new Dependency(dependencyElement));
}
List<Element> springDependencies = XmlUtils.findElements("/configuration/spring/dependencies/dependency", configuration);
for (Element dependencyElement : springDependencies) {
projectOperations.addDependency(new Dependency(dependencyElement));
}
if (database == JdbcDatabase.ORACLE || database == JdbcDatabase.DB2) {
logger.warning("The " + database.name() + " JDBC driver is not available in public maven repositories. Please adjust the pom.xml dependency to suit your needs");
}
}
private String getProjectName() {
return ((ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier())).getProjectName();
}
private void updateRepositories(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseRepositories = XmlUtils.findElements(getDbXPath(database) + "/repositories/repository", configuration);
for (Element repositoryElement : databaseRepositories) {
projectOperations.addRepository(new Repository(repositoryElement));
}
List<Element> ormRepositories = XmlUtils.findElements(getProviderXPath(ormProvider) + "/repositories/repository", configuration);
for (Element repositoryElement : ormRepositories) {
projectOperations.addRepository(new Repository(repositoryElement));
}
List<Element> jpaRepositories = XmlUtils.findElements("/configuration/persistence/provider[@id='JPA']/repositories/repository", configuration);
for (Element repositoryElement : jpaRepositories) {
projectOperations.addRepository(new Repository(repositoryElement));
}
}
private void updatePluginRepositories(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databasePluginRepositories = XmlUtils.findElements(getDbXPath(database) + "/pluginRepositories/pluginRepository", configuration);
for (Element pluginRepositoryElement : databasePluginRepositories) {
projectOperations.addPluginRepository(new Repository(pluginRepositoryElement));
}
List<Element> ormPluginRepositories = XmlUtils.findElements(getProviderXPath(ormProvider) + "/pluginRepositories/pluginRepository", configuration);
for (Element pluginRepositoryElement : ormPluginRepositories) {
projectOperations.addPluginRepository(new Repository(pluginRepositoryElement));
}
}
private void updateFilters(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseFilters = XmlUtils.findElements(getDbXPath(database) + "/filters/filter", configuration);
for (Element filterElement : databaseFilters) {
projectOperations.addFilter(new Filter(filterElement));
}
List<Element> ormFilters = XmlUtils.findElements(getProviderXPath(ormProvider) + "/filters/filter", configuration);
for (Element filterElement : ormFilters) {
projectOperations.addFilter(new Filter(filterElement));
}
}
private void updateResources(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseResources = XmlUtils.findElements(getDbXPath(database) + "/resources/resource", configuration);
for (Element resourceElement : databaseResources) {
projectOperations.addResource(new Resource(resourceElement));
}
List<Element> ormResources = XmlUtils.findElements(getProviderXPath(ormProvider) + "/resources/resource", configuration);
for (Element resourceElement : ormResources) {
projectOperations.addResource(new Resource(resourceElement));
}
}
private void updateBuildPlugins(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databasePlugins = XmlUtils.findElements(getDbXPath(database) + "/plugins/plugin", configuration);
for (Element pluginElement : databasePlugins) {
projectOperations.addBuildPlugin(new Plugin(pluginElement));
}
List<Element> ormPlugins = XmlUtils.findElements(getProviderXPath(ormProvider) + "/plugins/plugin", configuration);
for (Element pluginElement : ormPlugins) {
projectOperations.addBuildPlugin(new Plugin(pluginElement));
}
if (database == JdbcDatabase.GOOGLE_APP_ENGINE) {
updateEclipsePlugin(true);
}
}
private void updateEclipsePlugin(boolean addBuildCommand) {
String pomPath = pathResolver.getIdentifier(Path.ROOT, "pom.xml");
MutableFile pomMutableFile = null;
Document pom;
try {
if (fileManager.exists(pomPath)) {
pomMutableFile = fileManager.updateFile(pomPath);
pom = XmlUtils.getDocumentBuilder().parse(pomMutableFile.getInputStream());
} else {
throw new IllegalStateException("Could not acquire pom.xml in " + pomPath);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = pom.getDocumentElement();
String gaeBuildCommandName = "com.google.appengine.eclipse.core.enhancerbuilder";
Element additionalBuildcommandsElement = XmlUtils.findFirstElement("/project/build/plugins/plugin[artifactId = 'maven-eclipse-plugin']/configuration/additionalBuildcommands", root);
Assert.notNull(additionalBuildcommandsElement, "additionalBuildcommands element of the maven-eclipse-plugin reqired");
Element buildCommandElement = XmlUtils.findFirstElement("buildCommand[name = '" + gaeBuildCommandName + "']", additionalBuildcommandsElement);
if (addBuildCommand && buildCommandElement == null) {
Element nameElement = pom.createElement("name");
nameElement.setTextContent(gaeBuildCommandName);
buildCommandElement = pom.createElement("buildCommand");
buildCommandElement.appendChild(nameElement);
additionalBuildcommandsElement.appendChild(buildCommandElement);
XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}
if (!addBuildCommand && buildCommandElement != null) {
additionalBuildcommandsElement.removeChild(buildCommandElement);
XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}
}
private void cleanup(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
for (JdbcDatabase jdbcDatabase : JdbcDatabase.values()) {
if (!jdbcDatabase.getKey().equals(database.getKey()) && !jdbcDatabase.getDriverClassName().equals(database.getDriverClassName())) {
List<Element> dependencies = XmlUtils.findElements(getDbXPath(jdbcDatabase) + "/dependencies/dependency", configuration);
for (Element dependencyElement : dependencies) {
projectOperations.removeDependency(new Dependency(dependencyElement));
}
List<Element> filters = XmlUtils.findElements(getDbXPath(jdbcDatabase) + "/filters/filter", configuration);
for (Element filterElement : filters) {
projectOperations.removeFilter(new Filter(filterElement));
}
List<Element> plugins = XmlUtils.findElements(getDbXPath(jdbcDatabase) + "/plugins/plugin", configuration);
for (Element pluginElement : plugins) {
projectOperations.removeBuildPlugin(new Plugin(pluginElement));
}
}
}
for (OrmProvider provider : OrmProvider.values()) {
if (provider != ormProvider) {
// List<Element> pomProperties = XmlUtils.findElements(getProviderXPath(provider) + "/properties/*", configuration);
// for (Element propertyElement : pomProperties) {
// projectOperations.removeProperty(new Property(propertyElement));
// }
List<Element> dependencies = XmlUtils.findElements(getProviderXPath(provider) + "/dependencies/dependency", configuration);
for (Element dependencyElement : dependencies) {
projectOperations.removeDependency(new Dependency(dependencyElement));
}
List<Element> filters = XmlUtils.findElements(getProviderXPath(provider) + "/filters/filter", configuration);
for (Element filterElement : filters) {
projectOperations.removeFilter(new Filter(filterElement));
}
List<Element> plugins = XmlUtils.findElements(getProviderXPath(provider) + "/plugins/plugin", configuration);
for (Element pluginElement : plugins) {
projectOperations.removeBuildPlugin(new Plugin(pluginElement));
}
}
}
if (database != JdbcDatabase.GOOGLE_APP_ENGINE) {
updateEclipsePlugin(false);
}
}
private String getDbXPath(JdbcDatabase database) {
return "/configuration/databases/database[@id = '" + database.getKey() + "']";
}
private String getProviderXPath(OrmProvider provider) {
return "/configuration/ormProviders/provider[@id = '" + provider.name() + "']";
}
private Element createPropertyElement(String name, String value, Document doc) {
Element property = doc.createElement("property");
property.setAttribute("name", name);
property.setAttribute("value", value);
return property;
}
private Element createRefElement(String name, String value, Document doc) {
Element property = doc.createElement("property");
property.setAttribute("name", name);
property.setAttribute("ref", value);
return property;
}
private SortedSet<String> getPropertiesFromDataNucleusConfiguration() {
String persistenceXmlPath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
if (!fileManager.exists(persistenceXmlPath)) {
throw new IllegalStateException("Failed to find " + persistenceXmlPath);
}
FileDetails fileDetails = fileManager.readFile(persistenceXmlPath);
Document document = null;
try {
InputStream is = new FileInputStream(fileDetails.getFile());
DocumentBuilder builder = XmlUtils.getDocumentBuilder();
builder.setErrorHandler(null);
document = builder.parse(is);
} catch (Exception e) {
throw new IllegalStateException(e);
}
List<Element> propertyElements = XmlUtils.findElements("/persistence/persistence-unit/properties/property", document.getDocumentElement());
Assert.notEmpty(propertyElements, "Failed to find property elements in " + persistenceXmlPath);
SortedSet<String> properties = new TreeSet<String>();
for (Element propertyElement : propertyElements) {
String key = propertyElement.getAttribute("name");
String value = propertyElement.getAttribute("value");
if ("datanucleus.ConnectionDriverName".equals(key)) {
properties.add("datanucleus.ConnectionDriverName = " + value);
}
if ("datanucleus.ConnectionURL".equals(key)) {
properties.add("datanucleus.ConnectionURL = " + value);
}
if ("datanucleus.ConnectionUserName".equals(key)) {
properties.add("datanucleus.ConnectionUserName = " + value);
}
if ("datanucleus.ConnectionPassword".equals(key)) {
properties.add("datanucleus.ConnectionPassword = " + value);
}
}
return properties;
}
}
| addon-jpa/src/main/java/org/springframework/roo/addon/jpa/JpaOperationsImpl.java | package org.springframework.roo.addon.jpa;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.springframework.roo.addon.propfiles.PropFileOperations;
import org.springframework.roo.file.monitor.event.FileDetails;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.process.manager.FileManager;
import org.springframework.roo.process.manager.MutableFile;
import org.springframework.roo.project.Dependency;
import org.springframework.roo.project.Filter;
import org.springframework.roo.project.Path;
import org.springframework.roo.project.PathResolver;
import org.springframework.roo.project.Plugin;
import org.springframework.roo.project.ProjectMetadata;
import org.springframework.roo.project.ProjectOperations;
import org.springframework.roo.project.Property;
import org.springframework.roo.project.Repository;
import org.springframework.roo.project.Resource;
import org.springframework.roo.support.logging.HandlerUtils;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.FileCopyUtils;
import org.springframework.roo.support.util.StringUtils;
import org.springframework.roo.support.util.TemplateUtils;
import org.springframework.roo.support.util.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Provides JPA configuration operations.
*
* @author Stefan Schmidt
* @author Alan Stewart
* @since 1.0
*/
@Component
@Service
public class JpaOperationsImpl implements JpaOperations {
private static final Logger logger = HandlerUtils.getLogger(JpaOperationsImpl.class);
private static final String PERSISTENCE_UNIT = "persistence-unit";
private static final String GAE_PERSISTENCE_UNIT_NAME = "transactions-optional";
private static final String PERSISTENCE_UNIT_NAME = "persistenceUnit";
@Reference private FileManager fileManager;
@Reference private PathResolver pathResolver;
@Reference private MetadataService metadataService;
@Reference private ProjectOperations projectOperations;
@Reference private PropFileOperations propFileOperations;
public boolean isJpaInstallationPossible() {
return metadataService.get(ProjectMetadata.getProjectIdentifier()) != null && !fileManager.exists(pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml"));
}
public boolean isJpaInstalled() {
return metadataService.get(ProjectMetadata.getProjectIdentifier()) != null && fileManager.exists(pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml"));
}
public boolean hasDatabaseProperties() {
return fileManager.exists(getDatabasePropertiesPath());
}
public SortedSet<String> getDatabaseProperties() {
if (fileManager.exists(getDatabasePropertiesPath())) {
return propFileOperations.getPropertyKeys(Path.SPRING_CONFIG_ROOT, "database.properties", true);
} else {
return getPropertiesFromDataNucleusConfiguration();
}
}
private String getDatabasePropertiesPath() {
return pathResolver.getIdentifier(Path.SPRING_CONFIG_ROOT, "database.properties");
}
public void configureJpa(OrmProvider ormProvider, JdbcDatabase database, String jndi, String applicationId, String hostName, String databaseName, String userName, String password, String persistenceUnit) {
Assert.notNull(ormProvider, "ORM provider required");
Assert.notNull(database, "JDBC database required");
// Parse the configuration.xml file
Element configuration = XmlUtils.getConfiguration(getClass());
// Remove unnecessary artifacts not specific to current database and JPA provider
cleanup(configuration, ormProvider, database);
updateApplicationContext(ormProvider, database, jndi, persistenceUnit);
updatePersistenceXml(ormProvider, database, databaseName, userName, password, persistenceUnit);
updateGaeXml(ormProvider, database, applicationId);
updateVMforceConfigProperties(ormProvider, database, userName, password);
if (!StringUtils.hasText(jndi)) {
updateDatabaseProperties(ormProvider, database, hostName, databaseName, userName, password);
}
updateLog4j(ormProvider);
updatePomProperties(configuration, ormProvider, database);
updateDependencies(configuration, ormProvider, database);
updateRepositories(configuration, ormProvider, database);
updatePluginRepositories(configuration, ormProvider, database);
updateFilters(configuration, ormProvider, database);
updateResources(configuration, ormProvider, database);
updateBuildPlugins(configuration, ormProvider, database);
}
private void updateApplicationContext(OrmProvider ormProvider, JdbcDatabase database, String jndi, String persistenceUnit) {
String contextPath = pathResolver.getIdentifier(Path.SPRING_CONFIG_ROOT, "applicationContext.xml");
MutableFile contextMutableFile = null;
Document appCtx;
try {
if (fileManager.exists(contextPath)) {
contextMutableFile = fileManager.updateFile(contextPath);
appCtx = XmlUtils.getDocumentBuilder().parse(contextMutableFile.getInputStream());
} else {
throw new IllegalStateException("Could not acquire applicationContext.xml in " + contextPath);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = appCtx.getDocumentElement();
// Checking for existence of configurations, if found abort
Element dataSource = XmlUtils.findFirstElement("/beans/bean[@id = 'dataSource']", root);
Element dataSourceJndi = XmlUtils.findFirstElement("/beans/jndi-lookup[@id = 'dataSource']", root);
if (ormProvider == OrmProvider.DATANUCLEUS || ormProvider == OrmProvider.DATANUCLEUS_2) {
if (dataSource != null) {
root.removeChild(dataSource);
}
if (dataSourceJndi != null) {
root.removeChild(dataSourceJndi);
}
} else if (!StringUtils.hasText(jndi) && dataSource == null) {
dataSource = appCtx.createElement("bean");
dataSource.setAttribute("class", "org.apache.commons.dbcp.BasicDataSource");
dataSource.setAttribute("destroy-method", "close");
dataSource.setAttribute("id", "dataSource");
dataSource.appendChild(createPropertyElement("driverClassName", "${database.driverClassName}", appCtx));
dataSource.appendChild(createPropertyElement("url", "${database.url}", appCtx));
dataSource.appendChild(createPropertyElement("username", "${database.username}", appCtx));
dataSource.appendChild(createPropertyElement("password", "${database.password}", appCtx));
root.appendChild(dataSource);
if (dataSourceJndi != null) {
dataSourceJndi.getParentNode().removeChild(dataSourceJndi);
}
} else if (StringUtils.hasText(jndi)) {
if (dataSourceJndi == null) {
dataSourceJndi = appCtx.createElement("jee:jndi-lookup");
dataSourceJndi.setAttribute("id", "dataSource");
root.appendChild(dataSourceJndi);
}
dataSourceJndi.setAttribute("jndi-name", jndi);
if (dataSource != null) {
dataSource.getParentNode().removeChild(dataSource);
}
}
if (dataSource != null) {
Element validationQueryElement = XmlUtils.findFirstElement("property[@name = 'validationQuery']", dataSource);
Element testOnBorrowElement = XmlUtils.findFirstElement("property[@name = 'testOnBorrow']", dataSource);
if (database != JdbcDatabase.MYSQL && validationQueryElement != null && testOnBorrowElement != null) {
dataSource.removeChild(validationQueryElement);
dataSource.removeChild(testOnBorrowElement);
} else if (database == JdbcDatabase.MYSQL && validationQueryElement == null && testOnBorrowElement == null) {
dataSource.appendChild(createPropertyElement("validationQuery", "SELECT 1 FROM DUAL", appCtx));
dataSource.appendChild(createPropertyElement("testOnBorrow", "true", appCtx));
}
}
Element transactionManager = XmlUtils.findFirstElement("/beans/bean[@id = 'transactionManager']", root);
if (transactionManager == null) {
transactionManager = appCtx.createElement("bean");
transactionManager.setAttribute("id", "transactionManager");
transactionManager.setAttribute("class", "org.springframework.orm.jpa.JpaTransactionManager");
transactionManager.appendChild(createRefElement("entityManagerFactory", "entityManagerFactory", appCtx));
root.appendChild(transactionManager);
}
Element aspectJTxManager = XmlUtils.findFirstElement("/beans/annotation-driven", root);
if (aspectJTxManager == null) {
aspectJTxManager = appCtx.createElement("tx:annotation-driven");
aspectJTxManager.setAttribute("mode", "aspectj");
aspectJTxManager.setAttribute("transaction-manager", "transactionManager");
root.appendChild(aspectJTxManager);
}
Element entityManagerFactory = XmlUtils.findFirstElement("/beans/bean[@id = 'entityManagerFactory']", root);
if (entityManagerFactory != null) {
root.removeChild(entityManagerFactory);
}
entityManagerFactory = appCtx.createElement("bean");
entityManagerFactory.setAttribute("id", "entityManagerFactory");
switch (database) {
case GOOGLE_APP_ENGINE:
entityManagerFactory.setAttribute("class", "org.springframework.orm.jpa.LocalEntityManagerFactoryBean");
entityManagerFactory.appendChild(createPropertyElement("persistenceUnitName", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : GAE_PERSISTENCE_UNIT_NAME), appCtx));
break;
default:
entityManagerFactory.setAttribute("class", "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean");
switch (ormProvider) {
case DATANUCLEUS:
case DATANUCLEUS_2:
entityManagerFactory.appendChild(createPropertyElement("persistenceUnitName", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : PERSISTENCE_UNIT_NAME), appCtx));
break;
default:
entityManagerFactory.appendChild(createRefElement("dataSource", "dataSource", appCtx));
break;
}
break;
}
root.appendChild(entityManagerFactory);
XmlUtils.removeTextNodes(root);
XmlUtils.writeXml(contextMutableFile.getOutputStream(), appCtx);
}
private void updatePersistenceXml(OrmProvider ormProvider, JdbcDatabase database, String databaseName, String userName, String password, String persistenceUnit) {
String persistencePath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
MutableFile persistenceMutableFile = null;
Document persistence;
try {
if (fileManager.exists(persistencePath)) {
persistenceMutableFile = fileManager.updateFile(persistencePath);
persistence = XmlUtils.getDocumentBuilder().parse(persistenceMutableFile.getInputStream());
} else {
persistenceMutableFile = fileManager.createFile(persistencePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "persistence-template.xml");
Assert.notNull(templateInputStream, "Could not acquire peristence.xml template");
persistence = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Properties dialects = new Properties();
try {
InputStream dialectsInputStream = TemplateUtils.getTemplate(getClass(), "jpa-dialects.properties");
Assert.notNull(dialectsInputStream, "Could not acquire jpa-dialects.properties");
dialects.load(dialectsInputStream);
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = persistence.getDocumentElement();
Element persistenceElement = XmlUtils.findFirstElement("/persistence", root);
Assert.notNull(persistenceElement, "No persistence element found");
Element persistenceUnitElement;
if (StringUtils.hasText(persistenceUnit)) {
persistenceUnitElement = XmlUtils.findFirstElement(PERSISTENCE_UNIT + "[@name = '" + persistenceUnit + "']", persistenceElement);
} else {
persistenceUnitElement = XmlUtils.findFirstElement(PERSISTENCE_UNIT + "[@name = '" + (database == JdbcDatabase.GOOGLE_APP_ENGINE ? GAE_PERSISTENCE_UNIT_NAME : PERSISTENCE_UNIT_NAME) + "']", persistenceElement);
}
if (persistenceUnitElement != null) {
while (persistenceUnitElement.getFirstChild() != null) {
persistenceUnitElement.removeChild(persistenceUnitElement.getFirstChild());
}
} else {
persistenceUnitElement = persistence.createElement(PERSISTENCE_UNIT);
persistenceElement.appendChild(persistenceUnitElement);
}
// Set attributes for DataNuclueus 1.1.x/GAE-specific requirements
switch (ormProvider) {
case DATANUCLEUS:
persistenceElement.setAttribute("version", "1.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd");
break;
default:
persistenceElement.setAttribute("version", "2.0");
persistenceElement.setAttribute("xsi:schemaLocation", "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
break;
}
// Add provider element
Element provider = persistence.createElement("provider");
switch (database) {
case GOOGLE_APP_ENGINE:
persistenceUnitElement.setAttribute("name", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : GAE_PERSISTENCE_UNIT_NAME));
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAlternateAdapter());
break;
case VMFORCE:
persistenceUnitElement.setAttribute("name", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : PERSISTENCE_UNIT_NAME));
persistenceUnitElement.removeAttribute("transaction-type");
provider.setTextContent(ormProvider.getAdapter());
break;
default:
persistenceUnitElement.setAttribute("name", (StringUtils.hasText(persistenceUnit) ? persistenceUnit : PERSISTENCE_UNIT_NAME));
persistenceUnitElement.setAttribute("transaction-type", "RESOURCE_LOCAL");
provider.setTextContent(ormProvider.getAdapter());
break;
}
persistenceUnitElement.appendChild(provider);
// Add properties
Element properties = persistence.createElement("properties");
switch (ormProvider) {
case HIBERNATE:
properties.appendChild(createPropertyElement("hibernate.dialect", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='create' to build a new database on each run; value='update' to modify an existing database; value='create-drop' means the same as 'create' but also drops tables when Hibernate closes; value='validate' makes no changes to the database")); // ROO-627
String hbm2dll = "create";
if (database == JdbcDatabase.DB2400) {
hbm2dll = "validate";
}
properties.appendChild(createPropertyElement("hibernate.hbm2ddl.auto", hbm2dll, persistence));
properties.appendChild(createPropertyElement("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy", persistence));
break;
case OPENJPA:
properties.appendChild(createPropertyElement("openjpa.jdbc.DBDictionary", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='buildSchema' to runtime forward map the DDL SQL; value='validate' makes no changes to the database")); // ROO-627
properties.appendChild(createPropertyElement("openjpa.jdbc.SynchronizeMappings", "buildSchema", persistence));
properties.appendChild(createPropertyElement("openjpa.RuntimeUnenhancedClasses", "supported", persistence));
break;
case ECLIPSELINK:
properties.appendChild(createPropertyElement("eclipselink.target-database", dialects.getProperty(ormProvider.name() + "." + database.name()), persistence));
properties.appendChild(persistence.createComment("value='drop-and-create-tables' to build a new database on each run; value='create-tables' creates new tables if needed; value='none' makes no changes to the database")); // ROO-627
properties.appendChild(createPropertyElement("eclipselink.ddl-generation", "drop-and-create-tables", persistence));
properties.appendChild(createPropertyElement("eclipselink.ddl-generation.output-mode", "database", persistence));
properties.appendChild(createPropertyElement("eclipselink.weaving", "static", persistence));
break;
case DATANUCLEUS:
case DATANUCLEUS_2:
String connectionString = database.getConnectionString();
switch (database) {
case GOOGLE_APP_ENGINE:
properties.appendChild(createPropertyElement("datanucleus.NontransactionalRead", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.NontransactionalWrite", "true", persistence));
break;
case VMFORCE:
userName = "${sfdc.userName}";
password = "${sfdc.password}";
properties.appendChild(createPropertyElement("datanucleus.Optimistic", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.datastoreTransactionDelayOperations", "true", persistence));
properties.appendChild(createPropertyElement("sfdcConnectionName", "DefaultSFDCConnection", persistence));
break;
default:
properties.appendChild(createPropertyElement("datanucleus.ConnectionDriverName", database.getDriverClassName(), persistence));
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
connectionString = connectionString.replace("TO_BE_CHANGED_BY_ADDON", projectMetadata.getProjectName());
switch (database) {
case HYPERSONIC_IN_MEMORY:
case HYPERSONIC_PERSISTENT:
case H2_IN_MEMORY:
userName = StringUtils.hasText(userName) ? userName : "sa";
break;
case DERBY:
break;
default:
logger.warning("Please enter your database details in src/main/resources/META-INF/persistence.xml.");
break;
}
properties.appendChild(createPropertyElement("datanucleus.storeManagerType", "rdbms", persistence));
}
properties.appendChild(createPropertyElement("datanucleus.ConnectionURL", connectionString, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionUserName", userName, persistence));
properties.appendChild(createPropertyElement("datanucleus.ConnectionPassword", password, persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateSchema", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateTables", "true", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateColumns", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.autoCreateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateTables", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.validateConstraints", "false", persistence));
properties.appendChild(createPropertyElement("datanucleus.jpa.addClassTransformer", "false", persistence));
break;
}
persistenceUnitElement.appendChild(properties);
XmlUtils.writeXml(persistenceMutableFile.getOutputStream(), persistence);
}
private void updateGaeXml(OrmProvider ormProvider, JdbcDatabase database, String applicationId) {
String appenginePath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/appengine-web.xml");
boolean appenginePathExists = fileManager.exists(appenginePath);
String loggingPropertiesPath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/logging.properties");
boolean loggingPropertiesPathExists = fileManager.exists(loggingPropertiesPath);
if (database != JdbcDatabase.GOOGLE_APP_ENGINE) {
if (appenginePathExists) {
fileManager.delete(appenginePath);
}
if (loggingPropertiesPathExists) {
fileManager.delete(loggingPropertiesPath);
}
return;
} else {
MutableFile appengineMutableFile = null;
Document appengine;
try {
if (appenginePathExists) {
appengineMutableFile = fileManager.updateFile(appenginePath);
appengine = XmlUtils.getDocumentBuilder().parse(appengineMutableFile.getInputStream());
} else {
appengineMutableFile = fileManager.createFile(appenginePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "appengine-web-template.xml");
Assert.notNull(templateInputStream, "Could not acquire appengine-web.xml template");
appengine = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element rootElement = appengine.getDocumentElement();
Element applicationElement = XmlUtils.findFirstElement("/appengine-web-app/application", rootElement);
applicationElement.setTextContent(StringUtils.hasText(applicationId) ? applicationId : getProjectName());
XmlUtils.writeXml(appengineMutableFile.getOutputStream(), appengine);
if (!loggingPropertiesPathExists) {
try {
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "logging.properties");
FileCopyUtils.copy(templateInputStream, fileManager.createFile(loggingPropertiesPath).getOutputStream());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
}
private void updateDatabaseProperties(OrmProvider ormProvider, JdbcDatabase database, String hostName, String databaseName, String userName, String password) {
String databasePath = getDatabasePropertiesPath();
boolean databaseExists = fileManager.exists(databasePath);
if (ormProvider == OrmProvider.DATANUCLEUS || ormProvider == OrmProvider.DATANUCLEUS_2) {
if (databaseExists) {
fileManager.delete(databasePath);
}
return;
}
MutableFile databaseMutableFile = null;
Properties props = new Properties();
try {
if (databaseExists) {
databaseMutableFile = fileManager.updateFile(databasePath);
props.load(databaseMutableFile.getInputStream());
} else {
databaseMutableFile = fileManager.createFile(databasePath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "database-template.properties");
Assert.notNull(templateInputStream, "Could not acquire database properties template");
props.load(templateInputStream);
}
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
props.put("database.driverClassName", database.getDriverClassName());
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
String connectionString = database.getConnectionString();
connectionString = connectionString.replace("TO_BE_CHANGED_BY_ADDON", projectMetadata.getProjectName());
if (StringUtils.hasText(databaseName)) {
// Oracle uses a different connection URL - see ROO-1203
String dbDelimiter = database == JdbcDatabase.ORACLE ? ":" : "/";
connectionString += databaseName.startsWith(dbDelimiter) ? databaseName : dbDelimiter + databaseName;
}
if (!StringUtils.hasText(hostName)) {
hostName = "localhost";
}
connectionString = connectionString.replace("HOST_NAME", hostName);
props.put("database.url", connectionString);
String dbPropsMsg = "Please enter your database details in src/main/resources/META-INF/spring/database.properties.";
switch (database) {
case HYPERSONIC_IN_MEMORY:
case HYPERSONIC_PERSISTENT:
case H2_IN_MEMORY:
userName = StringUtils.hasText(userName) ? userName : "sa";
break;
case DERBY:
break;
case SYBASE:
userName = StringUtils.hasText(userName) ? userName : "sa";
logger.warning(dbPropsMsg);
break;
default:
logger.warning(dbPropsMsg);
break;
}
props.put("database.username", StringUtils.trimToEmpty(userName));
props.put("database.password", StringUtils.trimToEmpty(password));
try {
props.store(databaseMutableFile.getOutputStream(), "Updated at " + new Date());
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void updateVMforceConfigProperties(OrmProvider ormProvider, JdbcDatabase database, String userName, String password) {
String configPath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "config.properties");
boolean configExists = fileManager.exists(configPath);
if (database != JdbcDatabase.VMFORCE) {
if (configExists) {
fileManager.delete(configPath);
}
return;
}
MutableFile configMutableFile = null;
Properties props = new Properties();
try {
if (configExists) {
configMutableFile = fileManager.updateFile(configPath);
props.load(configMutableFile.getInputStream());
} else {
configMutableFile = fileManager.createFile(configPath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "config-template.properties");
Assert.notNull(templateInputStream, "Could not acquire config properties template");
props.load(templateInputStream);
}
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
props.put("sfdc.userName", StringUtils.trimToEmpty(userName));
props.put("sfdc.password", StringUtils.trimToEmpty(password));
try {
props.store(configMutableFile.getOutputStream(), "Updated at " + new Date());
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void updateLog4j(OrmProvider ormProvider) {
try {
String log4jPath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "log4j.properties");
if (fileManager.exists(log4jPath)) {
MutableFile log4jMutableFile = fileManager.updateFile(log4jPath);
Properties props = new Properties();
props.load(log4jMutableFile.getInputStream());
final String dnKey = "log4j.category.DataNucleus";
if (ormProvider == OrmProvider.DATANUCLEUS && !props.containsKey(dnKey)) {
props.put(dnKey, "WARN");
props.store(log4jMutableFile.getOutputStream(), "Updated at " + new Date());
} else if (ormProvider != OrmProvider.DATANUCLEUS && props.containsKey(dnKey)) {
props.remove(dnKey);
props.store(log4jMutableFile.getOutputStream(), "Updated at " + new Date());
}
}
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private void updatePomProperties(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseProperties = XmlUtils.findElements(getDbXPath(database) + "/properties/*", configuration);
for (Element property : databaseProperties) {
projectOperations.addProperty(new Property(property));
}
List<Element> providerProperties = XmlUtils.findElements(getProviderXPath(ormProvider) + "/properties/*", configuration);
for (Element property : providerProperties) {
projectOperations.addProperty(new Property(property));
}
}
private void updateDependencies(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseDependencies = XmlUtils.findElements(getDbXPath(database) + "/dependencies/dependency", configuration);
for (Element dependencyElement : databaseDependencies) {
projectOperations.addDependency(new Dependency(dependencyElement));
}
List<Element> ormDependencies = XmlUtils.findElements(getProviderXPath(ormProvider) + "/dependencies/dependency", configuration);
for (Element dependencyElement : ormDependencies) {
projectOperations.addDependency(new Dependency(dependencyElement));
}
// Hard coded to JPA & Hibernate Validator for now
List<Element> jpaDependencies = XmlUtils.findElements("/configuration/persistence/provider[@id = 'JPA']/dependencies/dependency", configuration);
for (Element dependencyElement : jpaDependencies) {
projectOperations.addDependency(new Dependency(dependencyElement));
}
List<Element> springDependencies = XmlUtils.findElements("/configuration/spring/dependencies/dependency", configuration);
for (Element dependencyElement : springDependencies) {
projectOperations.addDependency(new Dependency(dependencyElement));
}
if (database == JdbcDatabase.ORACLE || database == JdbcDatabase.DB2) {
logger.warning("The " + database.name() + " JDBC driver is not available in public maven repositories. Please adjust the pom.xml dependency to suit your needs");
}
}
private String getProjectName() {
return ((ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier())).getProjectName();
}
private void updateRepositories(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseRepositories = XmlUtils.findElements(getDbXPath(database) + "/repositories/repository", configuration);
for (Element repositoryElement : databaseRepositories) {
projectOperations.addRepository(new Repository(repositoryElement));
}
List<Element> ormRepositories = XmlUtils.findElements(getProviderXPath(ormProvider) + "/repositories/repository", configuration);
for (Element repositoryElement : ormRepositories) {
projectOperations.addRepository(new Repository(repositoryElement));
}
List<Element> jpaRepositories = XmlUtils.findElements("/configuration/persistence/provider[@id='JPA']/repositories/repository", configuration);
for (Element repositoryElement : jpaRepositories) {
projectOperations.addRepository(new Repository(repositoryElement));
}
}
private void updatePluginRepositories(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databasePluginRepositories = XmlUtils.findElements(getDbXPath(database) + "/pluginRepositories/pluginRepository", configuration);
for (Element pluginRepositoryElement : databasePluginRepositories) {
projectOperations.addPluginRepository(new Repository(pluginRepositoryElement));
}
List<Element> ormPluginRepositories = XmlUtils.findElements(getProviderXPath(ormProvider) + "/pluginRepositories/pluginRepository", configuration);
for (Element pluginRepositoryElement : ormPluginRepositories) {
projectOperations.addPluginRepository(new Repository(pluginRepositoryElement));
}
}
private void updateFilters(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseFilters = XmlUtils.findElements(getDbXPath(database) + "/filters/filter", configuration);
for (Element filterElement : databaseFilters) {
projectOperations.addFilter(new Filter(filterElement));
}
List<Element> ormFilters = XmlUtils.findElements(getProviderXPath(ormProvider) + "/filters/filter", configuration);
for (Element filterElement : ormFilters) {
projectOperations.addFilter(new Filter(filterElement));
}
}
private void updateResources(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databaseResources = XmlUtils.findElements(getDbXPath(database) + "/resources/resource", configuration);
for (Element resourceElement : databaseResources) {
projectOperations.addResource(new Resource(resourceElement));
}
List<Element> ormResources = XmlUtils.findElements(getProviderXPath(ormProvider) + "/resources/resource", configuration);
for (Element resourceElement : ormResources) {
projectOperations.addResource(new Resource(resourceElement));
}
}
private void updateBuildPlugins(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
List<Element> databasePlugins = XmlUtils.findElements(getDbXPath(database) + "/plugins/plugin", configuration);
for (Element pluginElement : databasePlugins) {
projectOperations.addBuildPlugin(new Plugin(pluginElement));
}
List<Element> ormPlugins = XmlUtils.findElements(getProviderXPath(ormProvider) + "/plugins/plugin", configuration);
for (Element pluginElement : ormPlugins) {
projectOperations.addBuildPlugin(new Plugin(pluginElement));
}
if (database == JdbcDatabase.GOOGLE_APP_ENGINE) {
updateEclipsePlugin(true);
}
}
private void updateEclipsePlugin(boolean addBuildCommand) {
String pomPath = pathResolver.getIdentifier(Path.ROOT, "pom.xml");
MutableFile pomMutableFile = null;
Document pom;
try {
if (fileManager.exists(pomPath)) {
pomMutableFile = fileManager.updateFile(pomPath);
pom = XmlUtils.getDocumentBuilder().parse(pomMutableFile.getInputStream());
} else {
throw new IllegalStateException("Could not acquire pom.xml in " + pomPath);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = pom.getDocumentElement();
String gaeBuildCommandName = "com.google.appengine.eclipse.core.enhancerbuilder";
Element additionalBuildcommandsElement = XmlUtils.findFirstElement("/project/build/plugins/plugin[artifactId = 'maven-eclipse-plugin']/configuration/additionalBuildcommands", root);
Assert.notNull(additionalBuildcommandsElement, "additionalBuildcommands element of the maven-eclipse-plugin reqired");
Element buildCommandElement = XmlUtils.findFirstElement("buildCommand[name = '" + gaeBuildCommandName + "']", additionalBuildcommandsElement);
if (addBuildCommand && buildCommandElement == null) {
Element nameElement = pom.createElement("name");
nameElement.setTextContent(gaeBuildCommandName);
buildCommandElement = pom.createElement("buildCommand");
buildCommandElement.appendChild(nameElement);
additionalBuildcommandsElement.appendChild(buildCommandElement);
XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}
if (!addBuildCommand && buildCommandElement != null) {
additionalBuildcommandsElement.removeChild(buildCommandElement);
XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}
}
private void cleanup(Element configuration, OrmProvider ormProvider, JdbcDatabase database) {
for (JdbcDatabase jdbcDatabase : JdbcDatabase.values()) {
if (!jdbcDatabase.getKey().equals(database.getKey()) && !jdbcDatabase.getDriverClassName().equals(database.getDriverClassName())) {
List<Element> dependencies = XmlUtils.findElements(getDbXPath(jdbcDatabase) + "/dependencies/dependency", configuration);
for (Element dependencyElement : dependencies) {
projectOperations.removeDependency(new Dependency(dependencyElement));
}
List<Element> filters = XmlUtils.findElements(getDbXPath(jdbcDatabase) + "/filters/filter", configuration);
for (Element filterElement : filters) {
projectOperations.removeFilter(new Filter(filterElement));
}
List<Element> plugins = XmlUtils.findElements(getDbXPath(jdbcDatabase) + "/plugins/plugin", configuration);
for (Element pluginElement : plugins) {
projectOperations.removeBuildPlugin(new Plugin(pluginElement));
}
}
}
for (OrmProvider provider : OrmProvider.values()) {
if (provider != ormProvider) {
// List<Element> pomProperties = XmlUtils.findElements(getProviderXPath(provider) + "/properties/*", configuration);
// for (Element propertyElement : pomProperties) {
// projectOperations.removeProperty(new Property(propertyElement));
// }
List<Element> dependencies = XmlUtils.findElements(getProviderXPath(provider) + "/dependencies/dependency", configuration);
for (Element dependencyElement : dependencies) {
projectOperations.removeDependency(new Dependency(dependencyElement));
}
List<Element> filters = XmlUtils.findElements(getProviderXPath(provider) + "/filters/filter", configuration);
for (Element filterElement : filters) {
projectOperations.removeFilter(new Filter(filterElement));
}
List<Element> plugins = XmlUtils.findElements(getProviderXPath(provider) + "/plugins/plugin", configuration);
for (Element pluginElement : plugins) {
projectOperations.removeBuildPlugin(new Plugin(pluginElement));
}
}
}
if (database != JdbcDatabase.GOOGLE_APP_ENGINE) {
updateEclipsePlugin(false);
}
}
private String getDbXPath(JdbcDatabase database) {
return "/configuration/databases/database[@id = '" + database.getKey() + "']";
}
private String getProviderXPath(OrmProvider provider) {
return "/configuration/ormProviders/provider[@id = '" + provider.name() + "']";
}
private Element createPropertyElement(String name, String value, Document doc) {
Element property = doc.createElement("property");
property.setAttribute("name", name);
property.setAttribute("value", value);
return property;
}
private Element createRefElement(String name, String value, Document doc) {
Element property = doc.createElement("property");
property.setAttribute("name", name);
property.setAttribute("ref", value);
return property;
}
private SortedSet<String> getPropertiesFromDataNucleusConfiguration() {
String persistenceXmlPath = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
if (!fileManager.exists(persistenceXmlPath)) {
throw new IllegalStateException("Failed to find " + persistenceXmlPath);
}
FileDetails fileDetails = fileManager.readFile(persistenceXmlPath);
Document document = null;
try {
InputStream is = new FileInputStream(fileDetails.getFile());
DocumentBuilder builder = XmlUtils.getDocumentBuilder();
builder.setErrorHandler(null);
document = builder.parse(is);
} catch (Exception e) {
throw new IllegalStateException(e);
}
List<Element> propertyElements = XmlUtils.findElements("/persistence/persistence-unit/properties/property", document.getDocumentElement());
Assert.notEmpty(propertyElements, "Failed to find property elements in " + persistenceXmlPath);
SortedSet<String> properties = new TreeSet<String>();
for (Element propertyElement : propertyElements) {
String key = propertyElement.getAttribute("name");
String value = propertyElement.getAttribute("value");
if ("datanucleus.ConnectionDriverName".equals(key)) {
properties.add("datanucleus.ConnectionDriverName = " + value);
}
if ("datanucleus.ConnectionURL".equals(key)) {
properties.add("datanucleus.ConnectionURL = " + value);
}
if ("datanucleus.ConnectionUserName".equals(key)) {
properties.add("datanucleus.ConnectionUserName = " + value);
}
if ("datanucleus.ConnectionPassword".equals(key)) {
properties.add("datanucleus.ConnectionPassword = " + value);
}
}
return properties;
}
}
| ROO-1545: Using Hibernate on JBoss cause problems and does not work out-of-the-box
| addon-jpa/src/main/java/org/springframework/roo/addon/jpa/JpaOperationsImpl.java | ROO-1545: Using Hibernate on JBoss cause problems and does not work out-of-the-box |
|
Java | apache-2.0 | 22c7a5016f80b128e2967dfc1b16b529b3c155c1 | 0 | gathreya/rice-kc,cniesen/rice,bhutchinson/rice,gathreya/rice-kc,jwillia/kc-rice1,cniesen/rice,UniversityOfHawaiiORS/rice,bhutchinson/rice,ewestfal/rice-svn2git-test,kuali/kc-rice,smith750/rice,geothomasp/kualico-rice-kc,smith750/rice,bsmith83/rice-1,geothomasp/kualico-rice-kc,shahess/rice,shahess/rice,kuali/kc-rice,ewestfal/rice,kuali/kc-rice,gathreya/rice-kc,UniversityOfHawaiiORS/rice,smith750/rice,bsmith83/rice-1,jwillia/kc-rice1,bhutchinson/rice,ewestfal/rice,UniversityOfHawaiiORS/rice,smith750/rice,jwillia/kc-rice1,ewestfal/rice,sonamuthu/rice-1,cniesen/rice,rojlarge/rice-kc,jwillia/kc-rice1,cniesen/rice,shahess/rice,geothomasp/kualico-rice-kc,rojlarge/rice-kc,jwillia/kc-rice1,rojlarge/rice-kc,shahess/rice,bsmith83/rice-1,gathreya/rice-kc,ewestfal/rice,bhutchinson/rice,smith750/rice,gathreya/rice-kc,rojlarge/rice-kc,sonamuthu/rice-1,cniesen/rice,shahess/rice,ewestfal/rice-svn2git-test,rojlarge/rice-kc,sonamuthu/rice-1,kuali/kc-rice,kuali/kc-rice,geothomasp/kualico-rice-kc,geothomasp/kualico-rice-kc,ewestfal/rice-svn2git-test,UniversityOfHawaiiORS/rice,ewestfal/rice,bhutchinson/rice,UniversityOfHawaiiORS/rice,bsmith83/rice-1,sonamuthu/rice-1,ewestfal/rice-svn2git-test | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.sampleu.travel;
import org.kuali.rice.krad.data.util.Link;
import org.kuali.rice.krad.web.bind.ChangeTracking;
import org.kuali.rice.krad.web.form.TransactionalDocumentFormBase;
/**
* Transactional doc form implementation for the travel authorization document.
*
* <p>
* Holds properties necessary to determine the {@code View} instance that
* will be used to render the UI for the travel authorization document.
* </p>
*
* @author Kuali Rice Team ([email protected])
*/
@ChangeTracking
@Link(path = "document")
public class TravelAuthorizationForm extends TransactionalDocumentFormBase {
private static final long serialVersionUID = 6857088926834897587L;
private String travelerFirstName;
private String travelerLastName;
public TravelAuthorizationForm() {
super();
}
/**
* Determines the default type name.
*
* <p>
* The default document type name is specific for each type of KRAD transactional
* document and manually set.
* </p>
*
* @link TravelAuthorizationForm#getDefaultDocumentTypeName()
* @return String - default document type name
*/
@Override
protected String getDefaultDocumentTypeName() {
return "TravelAuthorization";
}
public void setTravelerFirstName(String travelerFirstName) {
this.travelerFirstName = travelerFirstName;
}
public String getTravelerFirstName() {
return travelerFirstName;
}
public void setTravelerLastName(String travelerLastName) {
this.travelerLastName = travelerLastName;
}
public String getTravelerLastName() {
return travelerLastName;
}
}
| rice-framework/krad-sampleapp/web/src/main/java/edu/sampleu/travel/TravelAuthorizationForm.java | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.sampleu.travel;
import org.kuali.rice.krad.web.form.TransactionalDocumentFormBase;
/**
* Transactional doc form implementation for the travel authorization document.
*
* <p>
* Holds properties necessary to determine the {@code View} instance that
* will be used to render the UI for the travel authorization document.
* </p>
*
* @author Kuali Rice Team ([email protected])
*/
public class TravelAuthorizationForm extends TransactionalDocumentFormBase {
private static final long serialVersionUID = 6857088926834897587L;
private String travelerFirstName;
private String travelerLastName;
public TravelAuthorizationForm() {
super();
}
/**
* Determines the default type name.
*
* <p>
* The default document type name is specific for each type of KRAD transactional
* document and manually set.
* </p>
*
* @link TravelAuthorizationForm#getDefaultDocumentTypeName()
* @return String - default document type name
*/
@Override
protected String getDefaultDocumentTypeName() {
return "TravelAuthorization";
}
public void setTravelerFirstName(String travelerFirstName) {
this.travelerFirstName = travelerFirstName;
}
public String getTravelerFirstName() {
return travelerFirstName;
}
public void setTravelerLastName(String travelerLastName) {
this.travelerLastName = travelerLastName;
}
public String getTravelerLastName() {
return travelerLastName;
}
}
| KULRICE-12479: Adding change tracking to our transactional document for further testing
| rice-framework/krad-sampleapp/web/src/main/java/edu/sampleu/travel/TravelAuthorizationForm.java | KULRICE-12479: Adding change tracking to our transactional document for further testing |
|
Java | apache-2.0 | b0e7399f905e3d69b73c58653b1360a199be248d | 0 | scwang90/SmartRefreshLayout | package com.scwang.refreshlayout;
import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatDelegate;
import com.scwang.refreshlayout.util.DynamicTimeFormat;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshInitializer;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.squareup.leakcanary.LeakCanary;
/**
*
* Created by SCWANG on 2017/6/11.
*/
public class App extends Application {
static {
//启用矢量图兼容
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
//设置全局默认配置(优先级最低,会被其他设置覆盖)
SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() {
@Override
public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) {
//全局设置(优先级最低)
layout.setEnableAutoLoadMore(true);
layout.setEnableOverScrollDrag(false);
layout.setEnableOverScrollBounce(true);
layout.setEnableLoadMoreWhenContentNotFull(true);
layout.setEnableScrollContentWhenRefreshed(true);
}
});
SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
@NonNull
@Override
public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
//全局设置主题颜色(优先级第二低,可以覆盖 DefaultRefreshInitializer 的配置,与下面的ClassicsHeader绑定)
layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
return new ClassicsHeader(context).setTimeFormat(new DynamicTimeFormat("更新于 %s"));
}
});
}
@Override
public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
}
}
| app/src/main/java/com/scwang/refreshlayout/App.java | package com.scwang.refreshlayout;
import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatDelegate;
import com.scwang.refreshlayout.util.DynamicTimeFormat;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshInitializer;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.squareup.leakcanary.LeakCanary;
/**
*
* Created by SCWANG on 2017/6/11.
*/
public class App extends Application {
static {
//启用矢量图兼容
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
//设置全局默认配置(优先级最低,会被其他设置覆盖)
SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() {
@Override
public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) {
//全局设置主题颜色(优先级最低)
layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
}
});
SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
@NonNull
@Override
public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
//全局设置主题颜色(优先级第二低,可以覆盖 DefaultRefreshInitializer 的配置,与下面的ClassicsHeader绑定)
layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
return new ClassicsHeader(context).setTimeFormat(new DynamicTimeFormat("更新于 %s"));
}
});
}
@Override
public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
}
}
| 修改demo全局默认配置
| app/src/main/java/com/scwang/refreshlayout/App.java | 修改demo全局默认配置 |
|
Java | apache-2.0 | b9852d228e200f00ef63fbe5eca484bc1500196f | 0 | google/postcss-rename,google/postcss-rename,google/closure-stylesheets | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.css.compiler.passes;
import com.google.common.collect.ImmutableSet;
import com.google.common.css.compiler.ast.CssCompilerPass;
import com.google.common.css.compiler.ast.CssDeclarationNode;
import com.google.common.css.compiler.ast.CssNode;
import com.google.common.css.compiler.ast.CssPropertyNode;
import com.google.common.css.compiler.ast.DefaultTreeVisitor;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.Property;
import com.google.common.css.compiler.ast.VisitController;
import java.util.Set;
/**
* CSS Compiler pass that checks that all properties in the stylesheet are
* either on the built-in recognized property list, or were whitelisted
* explicitly.
*
* @author [email protected] (Michael Bolin)
*/
public class VerifyRecognizedProperties extends DefaultTreeVisitor
implements CssCompilerPass {
private final Set<String> allowedUnrecognizedProperties;
private final VisitController visitController;
private final ErrorManager errorManager;
public VerifyRecognizedProperties(Set<String> allowedUnrecognizedProperties,
VisitController visitController, ErrorManager errorManager) {
this.allowedUnrecognizedProperties = ImmutableSet.copyOf(
allowedUnrecognizedProperties);
this.visitController = visitController;
this.errorManager = errorManager;
}
/**
* Checks whether the {@code Property} of {@code declarationNode} is a
* recognized property. If not, an error is reported.
*/
@Override
public boolean enterDeclaration(CssDeclarationNode declarationNode) {
// TODO(bolinfest): Associate CSS version with a Property so that this check
// can also verify the "compliance level." For example, it may want to
// enforce that all properties are CSS 2.1 or earlier.
CssPropertyNode propertyNode = declarationNode.getPropertyName();
Property property = propertyNode.getProperty();
String propertyName = property.getName();
// TODO(bolinfest): Have separate options to specify whether the star hack
// or underscore hack should be allowed. See:
// http://en.wikipedia.org/wiki/CSS_filter#Star_hack
// http://en.wikipedia.org/wiki/CSS_filter#Underscore_hack
//
// If the star or underscore hack is employed, consider the name without the
// hack character in determining whether it is a "recognized property."
if (propertyName.startsWith("*") || propertyName.startsWith("_")) {
propertyName = propertyName.substring(1);
property = Property.byName(propertyName);
}
if (!allowedUnrecognizedProperties.contains(property.getName())) {
if (!property.isRecognizedProperty()) {
reportError(String.format("%s is an unrecognized property",
property.getName()), propertyNode);
} else if (property.hasWarning()) {
errorManager.reportWarning(new GssError(
String.format(
"WARNING for use of CSS property %s: %s\n",
property.getName(), property.getWarning()),
propertyNode.getSourceCodeLocation()));
}
}
return true;
}
private void reportError(String message, CssNode node) {
errorManager.report(new GssError(message, node.getSourceCodeLocation()));
}
@Override
public void runPass() {
visitController.startVisit(this);
}
}
| src/com/google/common/css/compiler/passes/VerifyRecognizedProperties.java | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.css.compiler.passes;
import com.google.common.collect.ImmutableSet;
import com.google.common.css.compiler.ast.CssCompilerPass;
import com.google.common.css.compiler.ast.CssDeclarationNode;
import com.google.common.css.compiler.ast.CssNode;
import com.google.common.css.compiler.ast.CssPropertyNode;
import com.google.common.css.compiler.ast.DefaultTreeVisitor;
import com.google.common.css.compiler.ast.ErrorManager;
import com.google.common.css.compiler.ast.GssError;
import com.google.common.css.compiler.ast.Property;
import com.google.common.css.compiler.ast.VisitController;
import java.util.Set;
/**
* CSS Compiler pass that checks that all properties in the stylesheet are
* either on the built-in recognized property list, or were whitelisted
* explicitly.
*
* @author [email protected] (Michael Bolin)
*/
public class VerifyRecognizedProperties extends DefaultTreeVisitor
implements CssCompilerPass {
private final Set<String> allowedUnrecognizedProperties;
private final VisitController visitController;
private final ErrorManager errorManager;
public VerifyRecognizedProperties(Set<String> allowedUnrecognizedProperties,
VisitController visitController, ErrorManager errorManager) {
this.allowedUnrecognizedProperties = ImmutableSet.copyOf(
allowedUnrecognizedProperties);
this.visitController = visitController;
this.errorManager = errorManager;
}
/**
* Checks whether the {@code Property} of {@code declarationNode} is a
* recognized property. If not, an error is reported.
*/
@Override
public boolean enterDeclaration(CssDeclarationNode declarationNode) {
// TODO(bolinfest): Associate CSS version with a Property so that this check
// can also verify the "compliance level." For example, it may want to
// enforce that all properties are CSS 2.1 or earlier.
CssPropertyNode propertyNode = declarationNode.getPropertyName();
Property property = propertyNode.getProperty();
String propertyName = property.getName();
// TODO(bolinfest): Have separate options to specify whether the star hack
// or underscore hack should be allowed. See:
// http://en.wikipedia.org/wiki/CSS_filter#Star_hack
// http://en.wikipedia.org/wiki/CSS_filter#Underscore_hack
//
// If the star or underscore hack is employed, consider the name without the
// hack character in determining whether it is a "recognized property."
if (propertyName.startsWith("*") || propertyName.startsWith("_")) {
propertyName = propertyName.substring(1);
property = Property.byName(propertyName);
}
if (!property.isRecognizedProperty() &&
!allowedUnrecognizedProperties.contains(property.getName())) {
reportError(String.format("%s is an unrecognized property",
property.getName()), propertyNode);
} else if (property.hasWarning()) {
errorManager.reportWarning(new GssError(
String.format(
"WARNING for use of CSS property %s: %s\n",
property.getName(), property.getWarning()),
propertyNode.getSourceCodeLocation()));
}
return true;
}
private void reportError(String message, CssNode node) {
errorManager.report(new GssError(message, node.getSourceCodeLocation()));
}
@Override
public void runPass() {
visitController.startVisit(this);
}
}
| Suppress warning messages for whitelisted properties.
Tweak the CSS compiler to not complain about recognized properties with
warnings if they are whitelisted with
--allowed_unrecognized_properties. Property warnings are already
disabled with the --allow_unrecognized_properties flag (see
com.google.common.css.compiler.passes.PassRunner:177) so it makes sense
to overload this flag to also whitelist flags that are *technically*
recognized, but not supported.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=133199104
MOE_MIGRATED_REVID=133703695
| src/com/google/common/css/compiler/passes/VerifyRecognizedProperties.java | Suppress warning messages for whitelisted properties. |
|
Java | apache-2.0 | 81d8a887b0406380e469c76ed2e41022a6372dd7 | 0 | wwjiang007/hadoop,wwjiang007/hadoop,JingchengDu/hadoop,mapr/hadoop-common,apache/hadoop,apurtell/hadoop,mapr/hadoop-common,JingchengDu/hadoop,nandakumar131/hadoop,wwjiang007/hadoop,steveloughran/hadoop,JingchengDu/hadoop,mapr/hadoop-common,apurtell/hadoop,nandakumar131/hadoop,steveloughran/hadoop,steveloughran/hadoop,steveloughran/hadoop,apache/hadoop,wwjiang007/hadoop,apurtell/hadoop,wwjiang007/hadoop,nandakumar131/hadoop,apurtell/hadoop,JingchengDu/hadoop,steveloughran/hadoop,wwjiang007/hadoop,wwjiang007/hadoop,apache/hadoop,JingchengDu/hadoop,nandakumar131/hadoop,mapr/hadoop-common,mapr/hadoop-common,apurtell/hadoop,nandakumar131/hadoop,apurtell/hadoop,apurtell/hadoop,nandakumar131/hadoop,apache/hadoop,nandakumar131/hadoop,mapr/hadoop-common,apache/hadoop,apache/hadoop,JingchengDu/hadoop,steveloughran/hadoop,steveloughran/hadoop,JingchengDu/hadoop,mapr/hadoop-common,apache/hadoop | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.web;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_DEFAULT;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_KEY;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_KEY;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_DEFAULT;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_KEY;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.crypto.key.KeyProvider;
import org.apache.hadoop.crypto.key.KeyProviderTokenIssuer;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.CommonPathCapabilities;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.DelegationTokenRenewer;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FSInputStream;
import org.apache.hadoop.fs.FileEncryptionInfo;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.GlobalStorageStatistics;
import org.apache.hadoop.fs.GlobalStorageStatistics.StorageStatisticsProvider;
import org.apache.hadoop.fs.QuotaUsage;
import org.apache.hadoop.fs.PathCapabilities;
import org.apache.hadoop.fs.StorageStatistics;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.fs.permission.FsCreateModes;
import org.apache.hadoop.hdfs.DFSOpsCountStatistics;
import org.apache.hadoop.hdfs.DFSOpsCountStatistics.OpType;
import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.XAttrCodec;
import org.apache.hadoop.fs.XAttrSetFlag;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSUtilClient;
import org.apache.hadoop.hdfs.HAUtilClient;
import org.apache.hadoop.hdfs.HdfsKMSUtil;
import org.apache.hadoop.hdfs.client.DfsPathCapabilities;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.FileEncryptionInfoProto;
import org.apache.hadoop.hdfs.protocolPB.PBHelperClient;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.web.resources.*;
import org.apache.hadoop.hdfs.web.resources.HttpOpParam.Op;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.retry.RetryPolicies;
import org.apache.hadoop.io.retry.RetryPolicy;
import org.apache.hadoop.io.retry.RetryUtils;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.ipc.StandbyException;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.security.token.TokenSelector;
import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenSelector;
import org.apache.hadoop.security.token.DelegationTokenIssuer;
import org.apache.hadoop.util.JsonSerialization;
import org.apache.hadoop.util.KMSUtil;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import static org.apache.hadoop.fs.impl.PathCapabilitiesSupport.validatePathCapabilityArgs;
/** A FileSystem for HDFS over the web. */
public class WebHdfsFileSystem extends FileSystem
implements DelegationTokenRenewer.Renewable,
TokenAspect.TokenManagementDelegator, KeyProviderTokenIssuer {
public static final Logger LOG = LoggerFactory
.getLogger(WebHdfsFileSystem.class);
/** WebHdfs version. */
public static final int VERSION = 1;
/** Http URI: http://namenode:port/{PATH_PREFIX}/path/to/file */
public static final String PATH_PREFIX = "/" + WebHdfsConstants.WEBHDFS_SCHEME
+ "/v" + VERSION;
public static final String EZ_HEADER = "X-Hadoop-Accept-EZ";
public static final String FEFINFO_HEADER = "X-Hadoop-feInfo";
public static final String DFS_HTTP_POLICY_KEY = "dfs.http.policy";
/**
* Default connection factory may be overridden in tests to use smaller
* timeout values
*/
protected URLConnectionFactory connectionFactory;
@VisibleForTesting
public static final String CANT_FALLBACK_TO_INSECURE_MSG =
"The client is configured to only allow connecting to secure cluster";
private boolean canRefreshDelegationToken;
private UserGroupInformation ugi;
private URI uri;
private Token<?> delegationToken;
protected Text tokenServiceName;
private RetryPolicy retryPolicy = null;
private Path workingDir;
private Path cachedHomeDirectory;
private InetSocketAddress nnAddrs[];
private int currentNNAddrIndex;
private boolean disallowFallbackToInsecureCluster;
private boolean isInsecureCluster;
private String restCsrfCustomHeader;
private Set<String> restCsrfMethodsToIgnore;
private DFSOpsCountStatistics storageStatistics;
private KeyProvider testProvider;
private boolean isTLSKrb;
/**
* Return the protocol scheme for the FileSystem.
*
* @return <code>webhdfs</code>
*/
@Override
public String getScheme() {
return WebHdfsConstants.WEBHDFS_SCHEME;
}
/**
* return the underlying transport protocol (http / https).
*/
protected String getTransportScheme() {
return "http";
}
protected Text getTokenKind() {
return WebHdfsConstants.WEBHDFS_TOKEN_KIND;
}
@Override
public synchronized void initialize(URI uri, Configuration conf
) throws IOException {
super.initialize(uri, conf);
setConf(conf);
// set user and acl patterns based on configuration file
UserParam.setUserPattern(conf.get(
HdfsClientConfigKeys.DFS_WEBHDFS_USER_PATTERN_KEY,
HdfsClientConfigKeys.DFS_WEBHDFS_USER_PATTERN_DEFAULT));
AclPermissionParam.setAclPermissionPattern(conf.get(
HdfsClientConfigKeys.DFS_WEBHDFS_ACL_PERMISSION_PATTERN_KEY,
HdfsClientConfigKeys.DFS_WEBHDFS_ACL_PERMISSION_PATTERN_DEFAULT));
int connectTimeout = (int) conf.getTimeDuration(
HdfsClientConfigKeys.DFS_WEBHDFS_SOCKET_CONNECT_TIMEOUT_KEY,
URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT,
TimeUnit.MILLISECONDS);
int readTimeout = (int) conf.getTimeDuration(
HdfsClientConfigKeys.DFS_WEBHDFS_SOCKET_READ_TIMEOUT_KEY,
URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT,
TimeUnit.MILLISECONDS);
boolean isOAuth = conf.getBoolean(
HdfsClientConfigKeys.DFS_WEBHDFS_OAUTH_ENABLED_KEY,
HdfsClientConfigKeys.DFS_WEBHDFS_OAUTH_ENABLED_DEFAULT);
if(isOAuth) {
LOG.debug("Enabling OAuth2 in WebHDFS");
connectionFactory = URLConnectionFactory
.newOAuth2URLConnectionFactory(connectTimeout, readTimeout, conf);
} else {
LOG.debug("Not enabling OAuth2 in WebHDFS");
connectionFactory = URLConnectionFactory
.newDefaultURLConnectionFactory(connectTimeout, readTimeout, conf);
}
this.isTLSKrb = "HTTPS_ONLY".equals(conf.get(DFS_HTTP_POLICY_KEY));
ugi = UserGroupInformation.getCurrentUser();
this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
this.nnAddrs = resolveNNAddr();
boolean isHA = HAUtilClient.isClientFailoverConfigured(conf, this.uri);
boolean isLogicalUri = isHA && HAUtilClient.isLogicalUri(conf, this.uri);
// In non-HA or non-logical URI case, the code needs to call
// getCanonicalUri() in order to handle the case where no port is
// specified in the URI
this.tokenServiceName = isLogicalUri ?
HAUtilClient.buildTokenServiceForLogicalUri(uri, getScheme())
: SecurityUtil.buildTokenService(getCanonicalUri());
if (!isHA) {
this.retryPolicy =
RetryUtils.getDefaultRetryPolicy(
conf,
HdfsClientConfigKeys.HttpClient.RETRY_POLICY_ENABLED_KEY,
HdfsClientConfigKeys.HttpClient.RETRY_POLICY_ENABLED_DEFAULT,
HdfsClientConfigKeys.HttpClient.RETRY_POLICY_SPEC_KEY,
HdfsClientConfigKeys.HttpClient.RETRY_POLICY_SPEC_DEFAULT,
HdfsConstants.SAFEMODE_EXCEPTION_CLASS_NAME);
} else {
int maxFailoverAttempts = conf.getInt(
HdfsClientConfigKeys.HttpClient.FAILOVER_MAX_ATTEMPTS_KEY,
HdfsClientConfigKeys.HttpClient.FAILOVER_MAX_ATTEMPTS_DEFAULT);
int maxRetryAttempts = conf.getInt(
HdfsClientConfigKeys.HttpClient.RETRY_MAX_ATTEMPTS_KEY,
HdfsClientConfigKeys.HttpClient.RETRY_MAX_ATTEMPTS_DEFAULT);
int failoverSleepBaseMillis = conf.getInt(
HdfsClientConfigKeys.HttpClient.FAILOVER_SLEEPTIME_BASE_KEY,
HdfsClientConfigKeys.HttpClient.FAILOVER_SLEEPTIME_BASE_DEFAULT);
int failoverSleepMaxMillis = conf.getInt(
HdfsClientConfigKeys.HttpClient.FAILOVER_SLEEPTIME_MAX_KEY,
HdfsClientConfigKeys.HttpClient.FAILOVER_SLEEPTIME_MAX_DEFAULT);
this.retryPolicy = RetryPolicies
.failoverOnNetworkException(RetryPolicies.TRY_ONCE_THEN_FAIL,
maxFailoverAttempts, maxRetryAttempts, failoverSleepBaseMillis,
failoverSleepMaxMillis);
}
this.workingDir = makeQualified(new Path(getHomeDirectoryString(ugi)));
this.canRefreshDelegationToken = UserGroupInformation.isSecurityEnabled();
this.isInsecureCluster = !this.canRefreshDelegationToken;
this.disallowFallbackToInsecureCluster = !conf.getBoolean(
CommonConfigurationKeys.IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY,
CommonConfigurationKeys.IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT);
this.initializeRestCsrf(conf);
this.delegationToken = null;
storageStatistics = (DFSOpsCountStatistics) GlobalStorageStatistics.INSTANCE
.put(DFSOpsCountStatistics.NAME,
new StorageStatisticsProvider() {
@Override
public StorageStatistics provide() {
return new DFSOpsCountStatistics();
}
});
}
/**
* Initializes client-side handling of cross-site request forgery (CSRF)
* protection by figuring out the custom HTTP headers that need to be sent in
* requests and which HTTP methods are ignored because they do not require
* CSRF protection.
*
* @param conf configuration to read
*/
private void initializeRestCsrf(Configuration conf) {
if (conf.getBoolean(DFS_WEBHDFS_REST_CSRF_ENABLED_KEY,
DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT)) {
this.restCsrfCustomHeader = conf.getTrimmed(
DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_KEY,
DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_DEFAULT);
this.restCsrfMethodsToIgnore = new HashSet<>();
this.restCsrfMethodsToIgnore.addAll(getTrimmedStringList(conf,
DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_KEY,
DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_DEFAULT));
} else {
this.restCsrfCustomHeader = null;
this.restCsrfMethodsToIgnore = null;
}
}
/**
* Returns a list of strings from a comma-delimited configuration value.
*
* @param conf configuration to check
* @param name configuration property name
* @param defaultValue default value if no value found for name
* @return list of strings from comma-delimited configuration value, or an
* empty list if not found
*/
private static List<String> getTrimmedStringList(Configuration conf,
String name, String defaultValue) {
String valueString = conf.get(name, defaultValue);
if (valueString == null) {
return new ArrayList<>();
}
return new ArrayList<>(StringUtils.getTrimmedStringCollection(valueString));
}
@Override
public URI getCanonicalUri() {
return super.getCanonicalUri();
}
TokenSelector<DelegationTokenIdentifier> tokenSelector =
new AbstractDelegationTokenSelector<DelegationTokenIdentifier>(getTokenKind()){};
// the first getAuthParams() for a non-token op will either get the
// internal token from the ugi or lazy fetch one
protected synchronized Token<?> getDelegationToken() throws IOException {
if (delegationToken == null) {
Token<?> token = tokenSelector.selectToken(
new Text(getCanonicalServiceName()), ugi.getTokens());
// ugi tokens are usually indicative of a task which can't
// refetch tokens. even if ugi has credentials, don't attempt
// to get another token to match hdfs/rpc behavior
if (token != null) {
LOG.debug("Using UGI token: {}", token);
canRefreshDelegationToken = false;
} else {
if (canRefreshDelegationToken) {
token = getDelegationToken(null);
if (token != null) {
LOG.debug("Fetched new token: {}", token);
} else { // security is disabled
canRefreshDelegationToken = false;
isInsecureCluster = true;
}
}
}
setDelegationToken(token);
}
return delegationToken;
}
@VisibleForTesting
synchronized boolean replaceExpiredDelegationToken() throws IOException {
boolean replaced = false;
if (canRefreshDelegationToken) {
Token<?> token = getDelegationToken(null);
LOG.debug("Replaced expired token: {}", token);
setDelegationToken(token);
replaced = (token != null);
}
return replaced;
}
@Override
protected int getDefaultPort() {
return HdfsClientConfigKeys.DFS_NAMENODE_HTTP_PORT_DEFAULT;
}
@Override
public URI getUri() {
return this.uri;
}
@Override
protected URI canonicalizeUri(URI uri) {
return NetUtils.getCanonicalUri(uri, getDefaultPort());
}
/** @return the home directory */
@Deprecated
public static String getHomeDirectoryString(final UserGroupInformation ugi) {
return "/user/" + ugi.getShortUserName();
}
@Override
public Path getHomeDirectory() {
if (cachedHomeDirectory == null) {
final HttpOpParam.Op op = GetOpParam.Op.GETHOMEDIRECTORY;
try {
String pathFromDelegatedFS = new FsPathResponseRunner<String>(op, null){
@Override
String decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.getPath(json);
}
} .run();
cachedHomeDirectory = new Path(pathFromDelegatedFS).makeQualified(
this.getUri(), null);
} catch (IOException e) {
LOG.error("Unable to get HomeDirectory from original File System", e);
cachedHomeDirectory = new Path("/user/" + ugi.getShortUserName())
.makeQualified(this.getUri(), null);
}
}
return cachedHomeDirectory;
}
@Override
public synchronized Path getWorkingDirectory() {
return workingDir;
}
@Override
public synchronized void setWorkingDirectory(final Path dir) {
Path absolutePath = makeAbsolute(dir);
String result = absolutePath.toUri().getPath();
if (!DFSUtilClient.isValidName(result)) {
throw new IllegalArgumentException("Invalid DFS directory name " +
result);
}
workingDir = absolutePath;
}
private Path makeAbsolute(Path f) {
return f.isAbsolute()? f: new Path(workingDir, f);
}
static Map<?, ?> jsonParse(final HttpURLConnection c,
final boolean useErrorStream) throws IOException {
if (c.getContentLength() == 0) {
return null;
}
final InputStream in = useErrorStream ?
c.getErrorStream() : c.getInputStream();
if (in == null) {
throw new IOException("The " + (useErrorStream? "error": "input") +
" stream is null.");
}
try {
final String contentType = c.getContentType();
if (contentType != null) {
final MediaType parsed = MediaType.valueOf(contentType);
if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
throw new IOException("Content-Type \"" + contentType
+ "\" is incompatible with \"" + MediaType.APPLICATION_JSON
+ "\" (parsed=\"" + parsed + "\")");
}
}
return JsonSerialization.mapReader().readValue(in);
} finally {
in.close();
}
}
private static Map<?, ?> validateResponse(final HttpOpParam.Op op,
final HttpURLConnection conn, boolean unwrapException)
throws IOException {
final int code = conn.getResponseCode();
// server is demanding an authentication we don't support
if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
// match hdfs/rpc exception
throw new AccessControlException(conn.getResponseMessage());
}
if (code != op.getExpectedHttpResponseCode()) {
final Map<?, ?> m;
try {
m = jsonParse(conn, true);
} catch(Exception e) {
throw new IOException("Unexpected HTTP response: code=" + code + " != "
+ op.getExpectedHttpResponseCode() + ", " + op.toQueryString()
+ ", message=" + conn.getResponseMessage(), e);
}
if (m == null) {
throw new IOException("Unexpected HTTP response: code=" + code + " != "
+ op.getExpectedHttpResponseCode() + ", " + op.toQueryString()
+ ", message=" + conn.getResponseMessage());
} else if (m.get(RemoteException.class.getSimpleName()) == null) {
return m;
}
IOException re = JsonUtilClient.toRemoteException(m);
//check if exception is due to communication with a Standby name node
if (re.getMessage() != null && re.getMessage().endsWith(
StandbyException.class.getSimpleName())) {
LOG.trace("Detected StandbyException", re);
throw new IOException(re);
}
// extract UGI-related exceptions and unwrap InvalidToken
// the NN mangles these exceptions but the DN does not and may need
// to re-fetch a token if either report the token is expired
if (re.getMessage() != null && re.getMessage().startsWith(
SecurityUtil.FAILED_TO_GET_UGI_MSG_HEADER)) {
String[] parts = re.getMessage().split(":\\s+", 3);
re = new RemoteException(parts[1], parts[2]);
re = ((RemoteException)re).unwrapRemoteException(InvalidToken.class);
}
throw unwrapException? toIOException(re): re;
}
return null;
}
/**
* Covert an exception to an IOException.
*
* For a non-IOException, wrap it with IOException.
* For a RemoteException, unwrap it.
* For an IOException which is not a RemoteException, return it.
*/
private static IOException toIOException(Exception e) {
if (!(e instanceof IOException)) {
return new IOException(e);
}
final IOException ioe = (IOException)e;
if (!(ioe instanceof RemoteException)) {
return ioe;
}
return ((RemoteException)ioe).unwrapRemoteException();
}
private synchronized InetSocketAddress getCurrentNNAddr() {
return nnAddrs[currentNNAddrIndex];
}
/**
* Reset the appropriate state to gracefully fail over to another name node
*/
private synchronized void resetStateToFailOver() {
currentNNAddrIndex = (currentNNAddrIndex + 1) % nnAddrs.length;
}
/**
* Return a URL pointing to given path on the namenode.
*
* @param path to obtain the URL for
* @param query string to append to the path
* @return namenode URL referring to the given path
* @throws IOException on error constructing the URL
*/
private URL getNamenodeURL(String path, String query) throws IOException {
InetSocketAddress nnAddr = getCurrentNNAddr();
final URL url = new URL(getTransportScheme(), nnAddr.getHostName(),
nnAddr.getPort(), path + '?' + query);
LOG.trace("url={}", url);
return url;
}
private synchronized Param<?, ?>[] getAuthParameters(final HttpOpParam.Op op)
throws IOException {
List<Param<?,?>> authParams = Lists.newArrayList();
// Skip adding delegation token for token operations because these
// operations require authentication.
Token<?> token = null;
if (!op.getRequireAuth()) {
token = getDelegationToken();
}
if (token != null) {
authParams.add(new DelegationParam(token.encodeToUrlString()));
} else {
UserGroupInformation userUgi = ugi;
UserGroupInformation realUgi = userUgi.getRealUser();
if (realUgi != null) { // proxy user
authParams.add(new DoAsParam(userUgi.getShortUserName()));
userUgi = realUgi;
}
UserParam userParam = new UserParam((userUgi.getShortUserName()));
//in insecure, use user.name parameter, in secure, use spnego auth
if(isInsecureCluster) {
authParams.add(userParam);
}
}
return authParams.toArray(new Param<?,?>[0]);
}
URL toUrl(final HttpOpParam.Op op, final Path fspath,
final Param<?,?>... parameters) throws IOException {
//initialize URI path and query
final String path = PATH_PREFIX
+ (fspath == null? "/": makeQualified(fspath).toUri().getRawPath());
final String query = op.toQueryString()
+ Param.toSortedString("&", getAuthParameters(op))
+ Param.toSortedString("&", parameters);
final URL url = getNamenodeURL(path, query);
LOG.trace("url={}", url);
return url;
}
/**
* This class is for initialing a HTTP connection, connecting to server,
* obtaining a response, and also handling retry on failures.
*/
abstract class AbstractRunner<T> {
abstract protected URL getUrl() throws IOException;
protected final HttpOpParam.Op op;
private final boolean redirected;
protected ExcludeDatanodesParam excludeDatanodes =
new ExcludeDatanodesParam("");
private boolean checkRetry;
private String redirectHost;
private boolean followRedirect = true;
protected AbstractRunner(final HttpOpParam.Op op, boolean redirected) {
this.op = op;
this.redirected = redirected;
}
protected AbstractRunner(final HttpOpParam.Op op, boolean redirected,
boolean followRedirect) {
this(op, redirected);
this.followRedirect = followRedirect;
}
T run() throws IOException {
UserGroupInformation connectUgi = ugi.getRealUser();
if (connectUgi == null) {
connectUgi = ugi;
}
if (op.getRequireAuth()) {
connectUgi.checkTGTAndReloginFromKeytab();
}
try {
// the entire lifecycle of the connection must be run inside the
// doAs to ensure authentication is performed correctly
return connectUgi.doAs(
new PrivilegedExceptionAction<T>() {
@Override
public T run() throws IOException {
return runWithRetry();
}
});
} catch (InterruptedException e) {
throw new IOException(e);
}
}
/**
* Two-step requests redirected to a DN
*
* Create/Append:
* Step 1) Submit a Http request with neither auto-redirect nor data.
* Step 2) Submit another Http request with the URL from the Location header
* with data.
*
* The reason of having two-step create/append is for preventing clients to
* send out the data before the redirect. This issue is addressed by the
* "Expect: 100-continue" header in HTTP/1.1; see RFC 2616, Section 8.2.3.
* Unfortunately, there are software library bugs (e.g. Jetty 6 http server
* and Java 6 http client), which do not correctly implement "Expect:
* 100-continue". The two-step create/append is a temporary workaround for
* the software library bugs.
*
* Open/Checksum
* Also implements two-step connects for other operations redirected to
* a DN such as open and checksum
*/
protected HttpURLConnection connect(URL url) throws IOException {
//redirect hostname and port
redirectHost = null;
if (url.getProtocol().equals("http") &&
UserGroupInformation.isSecurityEnabled() &&
isTLSKrb) {
throw new IOException("Access denied: dfs.http.policy is HTTPS_ONLY.");
}
// resolve redirects for a DN operation unless already resolved
if (op.getRedirect() && !redirected) {
final HttpOpParam.Op redirectOp =
HttpOpParam.TemporaryRedirectOp.valueOf(op);
final HttpURLConnection conn = connect(redirectOp, url);
// application level proxy like httpfs might not issue a redirect
if (conn.getResponseCode() == op.getExpectedHttpResponseCode()) {
return conn;
}
try {
validateResponse(redirectOp, conn, false);
url = new URL(conn.getHeaderField("Location"));
redirectHost = url.getHost() + ":" + url.getPort();
} finally {
// TODO: consider not calling conn.disconnect() to allow connection reuse
// See http://tinyurl.com/java7-http-keepalive
conn.disconnect();
}
if (!followRedirect) {
return conn;
}
}
try {
final HttpURLConnection conn = connect(op, url);
// output streams will validate on close
if (!op.getDoOutput()) {
validateResponse(op, conn, false);
}
return conn;
} catch (IOException ioe) {
if (redirectHost != null) {
if (excludeDatanodes.getValue() != null) {
excludeDatanodes = new ExcludeDatanodesParam(redirectHost + ","
+ excludeDatanodes.getValue());
} else {
excludeDatanodes = new ExcludeDatanodesParam(redirectHost);
}
}
throw ioe;
}
}
private HttpURLConnection connect(final HttpOpParam.Op op, final URL url)
throws IOException {
final HttpURLConnection conn =
(HttpURLConnection)connectionFactory.openConnection(url);
final boolean doOutput = op.getDoOutput();
conn.setRequestMethod(op.getType().toString());
conn.setInstanceFollowRedirects(false);
if (restCsrfCustomHeader != null &&
!restCsrfMethodsToIgnore.contains(op.getType().name())) {
// The value of the header is unimportant. Only its presence matters.
conn.setRequestProperty(restCsrfCustomHeader, "\"\"");
}
conn.setRequestProperty(EZ_HEADER, "true");
switch (op.getType()) {
// if not sending a message body for a POST or PUT operation, need
// to ensure the server/proxy knows this
case POST:
case PUT: {
conn.setDoOutput(true);
if (!doOutput) {
// explicitly setting content-length to 0 won't do spnego!!
// opening and closing the stream will send "Content-Length: 0"
conn.getOutputStream().close();
} else {
conn.setRequestProperty("Content-Type",
MediaType.APPLICATION_OCTET_STREAM);
conn.setChunkedStreamingMode(32 << 10); //32kB-chunk
}
break;
}
default:
conn.setDoOutput(doOutput);
break;
}
conn.connect();
return conn;
}
private T runWithRetry() throws IOException {
/**
* Do the real work.
*
* There are three cases that the code inside the loop can throw an
* IOException:
*
* <ul>
* <li>The connection has failed (e.g., ConnectException,
* @see FailoverOnNetworkExceptionRetry for more details)</li>
* <li>The namenode enters the standby state (i.e., StandbyException).</li>
* <li>The server returns errors for the command (i.e., RemoteException)</li>
* </ul>
*
* The call to shouldRetry() will conduct the retry policy. The policy
* examines the exception and swallows it if it decides to rerun the work.
*/
for(int retry = 0; ; retry++) {
checkRetry = !redirected;
final URL url = getUrl();
try {
final HttpURLConnection conn = connect(url);
return getResponse(conn);
} catch (AccessControlException ace) {
// no retries for auth failures
throw ace;
} catch (InvalidToken it) {
// try to replace the expired token with a new one. the attempt
// to acquire a new token must be outside this operation's retry
// so if it fails after its own retries, this operation fails too.
if (op.getRequireAuth() || !replaceExpiredDelegationToken()) {
throw it;
}
} catch (IOException ioe) {
// Attempt to include the redirected node in the exception. If the
// attempt to recreate the exception fails, just use the original.
String node = redirectHost;
if (node == null) {
node = url.getAuthority();
}
try {
IOException newIoe = ioe.getClass().getConstructor(String.class)
.newInstance(node + ": " + ioe.getMessage());
newIoe.initCause(ioe.getCause());
newIoe.setStackTrace(ioe.getStackTrace());
ioe = newIoe;
} catch (NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
}
shouldRetry(ioe, retry);
}
}
}
private void shouldRetry(final IOException ioe, final int retry
) throws IOException {
InetSocketAddress nnAddr = getCurrentNNAddr();
if (checkRetry) {
try {
final RetryPolicy.RetryAction a = retryPolicy.shouldRetry(
ioe, retry, 0, true);
boolean isRetry =
a.action == RetryPolicy.RetryAction.RetryDecision.RETRY;
boolean isFailoverAndRetry =
a.action == RetryPolicy.RetryAction.RetryDecision.FAILOVER_AND_RETRY;
if (isRetry || isFailoverAndRetry) {
LOG.info("Retrying connect to namenode: {}. Already retried {}"
+ " time(s); retry policy is {}, delay {}ms.",
nnAddr, retry, retryPolicy, a.delayMillis);
if (isFailoverAndRetry) {
resetStateToFailOver();
}
Thread.sleep(a.delayMillis);
return;
}
} catch(Exception e) {
LOG.warn("Original exception is ", ioe);
throw toIOException(e);
}
}
throw toIOException(ioe);
}
abstract T getResponse(HttpURLConnection conn) throws IOException;
}
/**
* Abstract base class to handle path-based operations with params
*/
abstract class AbstractFsPathRunner<T> extends AbstractRunner<T> {
private final Path fspath;
private Param<?,?>[] parameters;
AbstractFsPathRunner(final HttpOpParam.Op op, final Path fspath,
Param<?,?>... parameters) {
super(op, false);
this.fspath = fspath;
this.parameters = parameters;
}
AbstractFsPathRunner(final HttpOpParam.Op op, Param<?,?>[] parameters,
final Path fspath) {
super(op, false);
this.fspath = fspath;
this.parameters = parameters;
}
protected void updateURLParameters(Param<?, ?>... p) {
this.parameters = p;
}
@Override
protected URL getUrl() throws IOException {
if (excludeDatanodes.getValue() != null) {
Param<?, ?>[] tmpParam = new Param<?, ?>[parameters.length + 1];
System.arraycopy(parameters, 0, tmpParam, 0, parameters.length);
tmpParam[parameters.length] = excludeDatanodes;
return toUrl(op, fspath, tmpParam);
} else {
return toUrl(op, fspath, parameters);
}
}
Path getFspath() {
return fspath;
}
}
/**
* Default path-based implementation expects no json response
*/
class FsPathRunner extends AbstractFsPathRunner<Void> {
FsPathRunner(Op op, Path fspath, Param<?,?>... parameters) {
super(op, fspath, parameters);
}
@Override
Void getResponse(HttpURLConnection conn) throws IOException {
return null;
}
}
/**
* Handle path-based operations with a json response
*/
abstract class FsPathResponseRunner<T> extends AbstractFsPathRunner<T> {
FsPathResponseRunner(final HttpOpParam.Op op, final Path fspath,
Param<?,?>... parameters) {
super(op, fspath, parameters);
}
FsPathResponseRunner(final HttpOpParam.Op op, Param<?,?>[] parameters,
final Path fspath) {
super(op, parameters, fspath);
}
@Override
final T getResponse(HttpURLConnection conn) throws IOException {
try {
final Map<?,?> json = jsonParse(conn, false);
if (json == null) {
// match exception class thrown by parser
throw new IllegalStateException("Missing response");
}
return decodeResponse(json);
} catch (IOException ioe) {
throw ioe;
} catch (Exception e) { // catch json parser errors
final IOException ioe =
new IOException("Response decoding failure: "+e.toString(), e);
LOG.debug("Response decoding failure.", e);
throw ioe;
} finally {
// Don't call conn.disconnect() to allow connection reuse
// See http://tinyurl.com/java7-http-keepalive
conn.getInputStream().close();
}
}
abstract T decodeResponse(Map<?,?> json) throws IOException;
}
/**
* Handle path-based operations with json boolean response
*/
class FsPathBooleanRunner extends FsPathResponseRunner<Boolean> {
FsPathBooleanRunner(Op op, Path fspath, Param<?,?>... parameters) {
super(op, fspath, parameters);
}
@Override
Boolean decodeResponse(Map<?,?> json) throws IOException {
return (Boolean)json.get("boolean");
}
}
/**
* Handle create/append output streams
*/
class FsPathOutputStreamRunner
extends AbstractFsPathRunner<FSDataOutputStream> {
private final int bufferSize;
FsPathOutputStreamRunner(Op op, Path fspath, int bufferSize,
Param<?,?>... parameters) {
super(op, fspath, parameters);
this.bufferSize = bufferSize;
}
@Override
FSDataOutputStream getResponse(final HttpURLConnection conn)
throws IOException {
return new FSDataOutputStream(new BufferedOutputStream(
conn.getOutputStream(), bufferSize), statistics) {
@Override
public void write(int b) throws IOException {
try {
super.write(b);
} catch (IOException e) {
LOG.warn("Write to output stream for file '{}' failed. "
+ "Attempting to fetch the cause from the connection.",
getFspath(), e);
validateResponse(op, conn, true);
throw e;
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
try {
super.write(b, off, len);
} catch (IOException e) {
LOG.warn("Write to output stream for file '{}' failed. "
+ "Attempting to fetch the cause from the connection.",
getFspath(), e);
validateResponse(op, conn, true);
throw e;
}
}
@Override
public void close() throws IOException {
try {
super.close();
} finally {
try {
validateResponse(op, conn, true);
} finally {
// This is a connection to DataNode. Let's disconnect since
// there is little chance that the connection will be reused
// any time soonl
conn.disconnect();
}
}
}
};
}
}
class FsPathConnectionRunner extends AbstractFsPathRunner<HttpURLConnection> {
FsPathConnectionRunner(Op op, Path fspath, Param<?,?>... parameters) {
super(op, fspath, parameters);
}
@Override
HttpURLConnection getResponse(final HttpURLConnection conn)
throws IOException {
return conn;
}
}
/**
* Used by open() which tracks the resolved url itself
*/
class URLRunner extends AbstractRunner<HttpURLConnection> {
private final URL url;
@Override
protected URL getUrl() throws IOException {
return url;
}
protected URLRunner(final HttpOpParam.Op op, final URL url,
boolean redirected, boolean followRedirect) {
super(op, redirected, followRedirect);
this.url = url;
}
@Override
HttpURLConnection getResponse(HttpURLConnection conn) throws IOException {
return conn;
}
}
private FsPermission applyUMask(FsPermission permission) {
if (permission == null) {
permission = FsPermission.getDefault();
}
return FsCreateModes.applyUMask(permission,
FsPermission.getUMask(getConf()));
}
private HdfsFileStatus getHdfsFileStatus(Path f) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETFILESTATUS;
HdfsFileStatus status = new FsPathResponseRunner<HdfsFileStatus>(op, f) {
@Override
HdfsFileStatus decodeResponse(Map<?,?> json) {
return JsonUtilClient.toFileStatus(json, true);
}
}.run();
if (status == null) {
throw new FileNotFoundException("File does not exist: " + f);
}
return status;
}
@Override
public FileStatus getFileStatus(Path f) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_FILE_STATUS);
return getHdfsFileStatus(f).makeQualified(getUri(), f);
}
@Override
public AclStatus getAclStatus(Path f) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETACLSTATUS;
AclStatus status = new FsPathResponseRunner<AclStatus>(op, f) {
@Override
AclStatus decodeResponse(Map<?,?> json) {
return JsonUtilClient.toAclStatus(json);
}
}.run();
if (status == null) {
throw new FileNotFoundException("File does not exist: " + f);
}
return status;
}
@Override
public boolean mkdirs(Path f, FsPermission permission) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.MKDIRS);
final HttpOpParam.Op op = PutOpParam.Op.MKDIRS;
final FsPermission modes = applyUMask(permission);
return new FsPathBooleanRunner(op, f,
new PermissionParam(modes.getMasked()),
new UnmaskedPermissionParam(modes.getUnmasked())
).run();
}
@Override
public boolean supportsSymlinks() {
return true;
}
/**
* Create a symlink pointing to the destination path.
*/
public void createSymlink(Path destination, Path f, boolean createParent
) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CREATE_SYM_LINK);
final HttpOpParam.Op op = PutOpParam.Op.CREATESYMLINK;
new FsPathRunner(op, f,
new DestinationParam(makeQualified(destination).toUri().getPath()),
new CreateParentParam(createParent)
).run();
}
@Override
public boolean rename(final Path src, final Path dst) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.RENAME);
final HttpOpParam.Op op = PutOpParam.Op.RENAME;
return new FsPathBooleanRunner(op, src,
new DestinationParam(makeQualified(dst).toUri().getPath())
).run();
}
@SuppressWarnings("deprecation")
@Override
public void rename(final Path src, final Path dst,
final Options.Rename... options) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.RENAME);
final HttpOpParam.Op op = PutOpParam.Op.RENAME;
new FsPathRunner(op, src,
new DestinationParam(makeQualified(dst).toUri().getPath()),
new RenameOptionSetParam(options)
).run();
}
@Override
public void setXAttr(Path p, String name, byte[] value,
EnumSet<XAttrSetFlag> flag) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_XATTR);
final HttpOpParam.Op op = PutOpParam.Op.SETXATTR;
if (value != null) {
new FsPathRunner(op, p, new XAttrNameParam(name), new XAttrValueParam(
XAttrCodec.encodeValue(value, XAttrCodec.HEX)),
new XAttrSetFlagParam(flag)).run();
} else {
new FsPathRunner(op, p, new XAttrNameParam(name),
new XAttrSetFlagParam(flag)).run();
}
}
@Override
public byte[] getXAttr(Path p, final String name) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_XATTR);
final HttpOpParam.Op op = GetOpParam.Op.GETXATTRS;
return new FsPathResponseRunner<byte[]>(op, p, new XAttrNameParam(name),
new XAttrEncodingParam(XAttrCodec.HEX)) {
@Override
byte[] decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.getXAttr(json);
}
}.run();
}
@Override
public Map<String, byte[]> getXAttrs(Path p) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETXATTRS;
return new FsPathResponseRunner<Map<String, byte[]>>(op, p,
new XAttrEncodingParam(XAttrCodec.HEX)) {
@Override
Map<String, byte[]> decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toXAttrs(json);
}
}.run();
}
@Override
public Map<String, byte[]> getXAttrs(Path p, final List<String> names)
throws IOException {
Preconditions.checkArgument(names != null && !names.isEmpty(),
"XAttr names cannot be null or empty.");
Param<?,?>[] parameters = new Param<?,?>[names.size() + 1];
for (int i = 0; i < parameters.length - 1; i++) {
parameters[i] = new XAttrNameParam(names.get(i));
}
parameters[parameters.length - 1] = new XAttrEncodingParam(XAttrCodec.HEX);
final HttpOpParam.Op op = GetOpParam.Op.GETXATTRS;
return new FsPathResponseRunner<Map<String, byte[]>>(op, parameters, p) {
@Override
Map<String, byte[]> decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toXAttrs(json);
}
}.run();
}
@Override
public List<String> listXAttrs(Path p) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.LISTXATTRS;
return new FsPathResponseRunner<List<String>>(op, p) {
@Override
List<String> decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toXAttrNames(json);
}
}.run();
}
@Override
public void removeXAttr(Path p, String name) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.REMOVE_XATTR);
final HttpOpParam.Op op = PutOpParam.Op.REMOVEXATTR;
new FsPathRunner(op, p, new XAttrNameParam(name)).run();
}
@Override
public void setOwner(final Path p, final String owner, final String group
) throws IOException {
if (owner == null && group == null) {
throw new IOException("owner == null && group == null");
}
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_OWNER);
final HttpOpParam.Op op = PutOpParam.Op.SETOWNER;
new FsPathRunner(op, p,
new OwnerParam(owner), new GroupParam(group)
).run();
}
@Override
public void setPermission(final Path p, final FsPermission permission
) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_PERMISSION);
final HttpOpParam.Op op = PutOpParam.Op.SETPERMISSION;
new FsPathRunner(op, p,new PermissionParam(permission)).run();
}
@Override
public void modifyAclEntries(Path path, List<AclEntry> aclSpec)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.MODIFY_ACL_ENTRIES);
final HttpOpParam.Op op = PutOpParam.Op.MODIFYACLENTRIES;
new FsPathRunner(op, path, new AclPermissionParam(aclSpec)).run();
}
@Override
public void removeAclEntries(Path path, List<AclEntry> aclSpec)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.REMOVE_ACL_ENTRIES);
final HttpOpParam.Op op = PutOpParam.Op.REMOVEACLENTRIES;
new FsPathRunner(op, path, new AclPermissionParam(aclSpec)).run();
}
@Override
public void removeDefaultAcl(Path path) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.REMOVE_DEFAULT_ACL);
final HttpOpParam.Op op = PutOpParam.Op.REMOVEDEFAULTACL;
new FsPathRunner(op, path).run();
}
@Override
public void removeAcl(Path path) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.REMOVE_ACL);
final HttpOpParam.Op op = PutOpParam.Op.REMOVEACL;
new FsPathRunner(op, path).run();
}
@Override
public void setAcl(final Path p, final List<AclEntry> aclSpec)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_ACL);
final HttpOpParam.Op op = PutOpParam.Op.SETACL;
new FsPathRunner(op, p, new AclPermissionParam(aclSpec)).run();
}
public void allowSnapshot(final Path p) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.ALLOW_SNAPSHOT);
final HttpOpParam.Op op = PutOpParam.Op.ALLOWSNAPSHOT;
new FsPathRunner(op, p).run();
}
@Override
public void satisfyStoragePolicy(final Path p) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SATISFY_STORAGE_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.SATISFYSTORAGEPOLICY;
new FsPathRunner(op, p).run();
}
public void enableECPolicy(String policyName) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.ENABLE_EC_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.ENABLEECPOLICY;
new FsPathRunner(op, null, new ECPolicyParam(policyName)).run();
}
public void disableECPolicy(String policyName) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.DISABLE_EC_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.DISABLEECPOLICY;
new FsPathRunner(op, null, new ECPolicyParam(policyName)).run();
}
public void setErasureCodingPolicy(Path p, String policyName)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_EC_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.SETECPOLICY;
new FsPathRunner(op, p, new ECPolicyParam(policyName)).run();
}
public void unsetErasureCodingPolicy(Path p) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.UNSET_EC_POLICY);
final HttpOpParam.Op op = PostOpParam.Op.UNSETECPOLICY;
new FsPathRunner(op, p).run();
}
public ErasureCodingPolicy getErasureCodingPolicy(Path p)
throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_EC_POLICY);
final HttpOpParam.Op op =GetOpParam.Op.GETECPOLICY;
return new FsPathResponseRunner<ErasureCodingPolicy>(op, p) {
@Override
ErasureCodingPolicy decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toECPolicy((Map<?, ?>) json);
}
}.run();
}
@Override
public Path createSnapshot(final Path path, final String snapshotName)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CREATE_SNAPSHOT);
final HttpOpParam.Op op = PutOpParam.Op.CREATESNAPSHOT;
return new FsPathResponseRunner<Path>(op, path,
new SnapshotNameParam(snapshotName)) {
@Override
Path decodeResponse(Map<?,?> json) {
return new Path((String) json.get(Path.class.getSimpleName()));
}
}.run();
}
public void disallowSnapshot(final Path p) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.DISALLOW_SNAPSHOT);
final HttpOpParam.Op op = PutOpParam.Op.DISALLOWSNAPSHOT;
new FsPathRunner(op, p).run();
}
@Override
public void deleteSnapshot(final Path path, final String snapshotName)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.DELETE_SNAPSHOT);
final HttpOpParam.Op op = DeleteOpParam.Op.DELETESNAPSHOT;
new FsPathRunner(op, path, new SnapshotNameParam(snapshotName)).run();
}
@Override
public void renameSnapshot(final Path path, final String snapshotOldName,
final String snapshotNewName) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.RENAME_SNAPSHOT);
final HttpOpParam.Op op = PutOpParam.Op.RENAMESNAPSHOT;
new FsPathRunner(op, path, new OldSnapshotNameParam(snapshotOldName),
new SnapshotNameParam(snapshotNewName)).run();
}
public SnapshotDiffReport getSnapshotDiffReport(final Path snapshotDir,
final String fromSnapshot, final String toSnapshot) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_SNAPSHOT_DIFF);
final HttpOpParam.Op op = GetOpParam.Op.GETSNAPSHOTDIFF;
return new FsPathResponseRunner<SnapshotDiffReport>(op, snapshotDir,
new OldSnapshotNameParam(fromSnapshot),
new SnapshotNameParam(toSnapshot)) {
@Override
SnapshotDiffReport decodeResponse(Map<?, ?> json) {
return JsonUtilClient.toSnapshotDiffReport(json);
}
}.run();
}
public SnapshottableDirectoryStatus[] getSnapshottableDirectoryList()
throws IOException {
statistics.incrementReadOps(1);
storageStatistics
.incrementOpCounter(OpType.GET_SNAPSHOTTABLE_DIRECTORY_LIST);
final HttpOpParam.Op op = GetOpParam.Op.GETSNAPSHOTTABLEDIRECTORYLIST;
return new FsPathResponseRunner<SnapshottableDirectoryStatus[]>(op, null) {
@Override
SnapshottableDirectoryStatus[] decodeResponse(Map<?, ?> json) {
return JsonUtilClient.toSnapshottableDirectoryList(json);
}
}.run();
}
@Override
public boolean setReplication(final Path p, final short replication
) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_REPLICATION);
final HttpOpParam.Op op = PutOpParam.Op.SETREPLICATION;
return new FsPathBooleanRunner(op, p,
new ReplicationParam(replication)
).run();
}
@Override
public void setTimes(final Path p, final long mtime, final long atime
) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_TIMES);
final HttpOpParam.Op op = PutOpParam.Op.SETTIMES;
new FsPathRunner(op, p,
new ModificationTimeParam(mtime),
new AccessTimeParam(atime)
).run();
}
@Override
public long getDefaultBlockSize() {
return getConf().getLongBytes(HdfsClientConfigKeys.DFS_BLOCK_SIZE_KEY,
HdfsClientConfigKeys.DFS_BLOCK_SIZE_DEFAULT);
}
@Override
public short getDefaultReplication() {
return (short)getConf().getInt(HdfsClientConfigKeys.DFS_REPLICATION_KEY,
HdfsClientConfigKeys.DFS_REPLICATION_DEFAULT);
}
@Override
public void concat(final Path trg, final Path [] srcs) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CONCAT);
final HttpOpParam.Op op = PostOpParam.Op.CONCAT;
new FsPathRunner(op, trg, new ConcatSourcesParam(srcs)).run();
}
@Override
public FSDataOutputStream create(final Path f, final FsPermission permission,
final boolean overwrite, final int bufferSize, final short replication,
final long blockSize, final Progressable progress) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CREATE);
final FsPermission modes = applyUMask(permission);
final HttpOpParam.Op op = PutOpParam.Op.CREATE;
return new FsPathOutputStreamRunner(op, f, bufferSize,
new PermissionParam(modes.getMasked()),
new UnmaskedPermissionParam(modes.getUnmasked()),
new OverwriteParam(overwrite),
new BufferSizeParam(bufferSize),
new ReplicationParam(replication),
new BlockSizeParam(blockSize)
).run();
}
@Override
public FSDataOutputStream createNonRecursive(final Path f,
final FsPermission permission, final EnumSet<CreateFlag> flag,
final int bufferSize, final short replication, final long blockSize,
final Progressable progress) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CREATE_NON_RECURSIVE);
final FsPermission modes = applyUMask(permission);
final HttpOpParam.Op op = PutOpParam.Op.CREATE;
return new FsPathOutputStreamRunner(op, f, bufferSize,
new PermissionParam(modes.getMasked()),
new UnmaskedPermissionParam(modes.getUnmasked()),
new CreateFlagParam(flag),
new CreateParentParam(false),
new BufferSizeParam(bufferSize),
new ReplicationParam(replication),
new BlockSizeParam(blockSize)
).run();
}
@Override
public FSDataOutputStream append(final Path f, final int bufferSize,
final Progressable progress) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.APPEND);
final HttpOpParam.Op op = PostOpParam.Op.APPEND;
return new FsPathOutputStreamRunner(op, f, bufferSize,
new BufferSizeParam(bufferSize)
).run();
}
@Override
public boolean truncate(Path f, long newLength) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.TRUNCATE);
final HttpOpParam.Op op = PostOpParam.Op.TRUNCATE;
return new FsPathBooleanRunner(op, f, new NewLengthParam(newLength)).run();
}
@Override
public boolean delete(Path f, boolean recursive) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.DELETE);
final HttpOpParam.Op op = DeleteOpParam.Op.DELETE;
return new FsPathBooleanRunner(op, f,
new RecursiveParam(recursive)
).run();
}
@SuppressWarnings("resource")
@Override
public FSDataInputStream open(final Path f, final int bufferSize
) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.OPEN);
WebHdfsInputStream webfsInputStream =
new WebHdfsInputStream(f, bufferSize);
if (webfsInputStream.getFileEncryptionInfo() == null) {
return new FSDataInputStream(webfsInputStream);
} else {
return new FSDataInputStream(
webfsInputStream.createWrappedInputStream());
}
}
@Override
public synchronized void close() throws IOException {
try {
if (canRefreshDelegationToken && delegationToken != null) {
cancelDelegationToken(delegationToken);
}
} catch (IOException ioe) {
LOG.debug("Token cancel failed: ", ioe);
} finally {
if (connectionFactory != null) {
connectionFactory.destroy();
}
super.close();
}
}
// use FsPathConnectionRunner to ensure retries for InvalidTokens
class UnresolvedUrlOpener extends ByteRangeInputStream.URLOpener {
private final FsPathConnectionRunner runner;
UnresolvedUrlOpener(FsPathConnectionRunner runner) {
super(null);
this.runner = runner;
}
@Override
protected HttpURLConnection connect(long offset, boolean resolved)
throws IOException {
assert offset == 0;
HttpURLConnection conn = runner.run();
setURL(conn.getURL());
return conn;
}
}
class OffsetUrlOpener extends ByteRangeInputStream.URLOpener {
OffsetUrlOpener(final URL url) {
super(url);
}
/** Setup offset url and connect. */
@Override
protected HttpURLConnection connect(final long offset,
final boolean resolved) throws IOException {
final URL offsetUrl = offset == 0L? url
: new URL(url + "&" + new OffsetParam(offset));
return new URLRunner(GetOpParam.Op.OPEN, offsetUrl, resolved,
true).run();
}
}
private static final String OFFSET_PARAM_PREFIX = OffsetParam.NAME + "=";
/** Remove offset parameter, if there is any, from the url */
static URL removeOffsetParam(final URL url) throws MalformedURLException {
String query = url.getQuery();
if (query == null) {
return url;
}
final String lower = StringUtils.toLowerCase(query);
if (!lower.startsWith(OFFSET_PARAM_PREFIX)
&& !lower.contains("&" + OFFSET_PARAM_PREFIX)) {
return url;
}
//rebuild query
StringBuilder b = null;
for(final StringTokenizer st = new StringTokenizer(query, "&");
st.hasMoreTokens();) {
final String token = st.nextToken();
if (!StringUtils.toLowerCase(token).startsWith(OFFSET_PARAM_PREFIX)) {
if (b == null) {
b = new StringBuilder("?").append(token);
} else {
b.append('&').append(token);
}
}
}
query = b == null? "": b.toString();
final String urlStr = url.toString();
return new URL(urlStr.substring(0, urlStr.indexOf('?')) + query);
}
static class OffsetUrlInputStream extends ByteRangeInputStream {
OffsetUrlInputStream(UnresolvedUrlOpener o, OffsetUrlOpener r)
throws IOException {
super(o, r);
}
/** Remove offset parameter before returning the resolved url. */
@Override
protected URL getResolvedUrl(final HttpURLConnection connection
) throws MalformedURLException {
return removeOffsetParam(connection.getURL());
}
}
/**
* Get {@link FileStatus} of files/directories in the given path. If path
* corresponds to a file then {@link FileStatus} of that file is returned.
* Else if path represents a directory then {@link FileStatus} of all
* files/directories inside given path is returned.
*
* @param f given path
* @return the statuses of the files/directories in the given path
*/
@Override
public FileStatus[] listStatus(final Path f) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.LIST_STATUS);
final URI fsUri = getUri();
final HttpOpParam.Op op = GetOpParam.Op.LISTSTATUS;
return new FsPathResponseRunner<FileStatus[]>(op, f) {
@Override
FileStatus[] decodeResponse(Map<?,?> json) {
HdfsFileStatus[] hdfsStatuses =
JsonUtilClient.toHdfsFileStatusArray(json);
final FileStatus[] statuses = new FileStatus[hdfsStatuses.length];
for (int i = 0; i < hdfsStatuses.length; i++) {
statuses[i] = hdfsStatuses[i].makeQualified(fsUri, f);
}
return statuses;
}
}.run();
}
private static final byte[] EMPTY_ARRAY = new byte[] {};
/**
* Get DirectoryEntries of the given path. DirectoryEntries contains an array
* of {@link FileStatus}, as well as iteration information.
*
* @param f given path
* @return DirectoryEntries for given path
*/
@Override
public DirectoryEntries listStatusBatch(Path f, byte[] token) throws
FileNotFoundException, IOException {
byte[] prevKey = EMPTY_ARRAY;
if (token != null) {
prevKey = token;
}
DirectoryListing listing = new FsPathResponseRunner<DirectoryListing>(
GetOpParam.Op.LISTSTATUS_BATCH,
f, new StartAfterParam(new String(prevKey, Charsets.UTF_8))) {
@Override
DirectoryListing decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toDirectoryListing(json);
}
}.run();
// Qualify the returned FileStatus array
final URI fsUri = getUri();
final HdfsFileStatus[] statuses = listing.getPartialListing();
FileStatus[] qualified = new FileStatus[statuses.length];
for (int i = 0; i < statuses.length; i++) {
qualified[i] = statuses[i].makeQualified(fsUri, f);
}
return new DirectoryEntries(qualified, listing.getLastName(),
listing.hasMore());
}
@Override
public Token<DelegationTokenIdentifier> getDelegationToken(
final String renewer) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETDELEGATIONTOKEN;
Token<DelegationTokenIdentifier> token =
new FsPathResponseRunner<Token<DelegationTokenIdentifier>>(
op, null, new RenewerParam(renewer)) {
@Override
Token<DelegationTokenIdentifier> decodeResponse(Map<?,?> json)
throws IOException {
return JsonUtilClient.toDelegationToken(json);
}
}.run();
if (token != null) {
token.setService(tokenServiceName);
} else {
if (disallowFallbackToInsecureCluster) {
throw new AccessControlException(CANT_FALLBACK_TO_INSECURE_MSG);
}
}
return token;
}
@Override
public DelegationTokenIssuer[] getAdditionalTokenIssuers()
throws IOException {
KeyProvider keyProvider = getKeyProvider();
if (keyProvider instanceof DelegationTokenIssuer) {
return new DelegationTokenIssuer[] {(DelegationTokenIssuer) keyProvider};
}
return null;
}
@Override
public synchronized Token<?> getRenewToken() {
return delegationToken;
}
@Override
public <T extends TokenIdentifier> void setDelegationToken(
final Token<T> token) {
synchronized (this) {
delegationToken = token;
}
}
@Override
public synchronized long renewDelegationToken(final Token<?> token
) throws IOException {
final HttpOpParam.Op op = PutOpParam.Op.RENEWDELEGATIONTOKEN;
return new FsPathResponseRunner<Long>(op, null,
new TokenArgumentParam(token.encodeToUrlString())) {
@Override
Long decodeResponse(Map<?,?> json) throws IOException {
return ((Number) json.get("long")).longValue();
}
}.run();
}
@Override
public synchronized void cancelDelegationToken(final Token<?> token
) throws IOException {
final HttpOpParam.Op op = PutOpParam.Op.CANCELDELEGATIONTOKEN;
new FsPathRunner(op, null,
new TokenArgumentParam(token.encodeToUrlString())
).run();
}
public BlockLocation[] getFileBlockLocations(final FileStatus status,
final long offset, final long length) throws IOException {
if (status == null) {
return null;
}
return getFileBlockLocations(status.getPath(), offset, length);
}
@Override
public BlockLocation[] getFileBlockLocations(final Path p,
final long offset, final long length) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_FILE_BLOCK_LOCATIONS);
final HttpOpParam.Op op = GetOpParam.Op.GET_BLOCK_LOCATIONS;
return new FsPathResponseRunner<BlockLocation[]>(op, p,
new OffsetParam(offset), new LengthParam(length)) {
@Override
BlockLocation[] decodeResponse(Map<?,?> json) throws IOException {
return DFSUtilClient.locatedBlocks2Locations(
JsonUtilClient.toLocatedBlocks(json));
}
}.run();
}
@Override
public Path getTrashRoot(Path path) {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_TRASH_ROOT);
final HttpOpParam.Op op = GetOpParam.Op.GETTRASHROOT;
try {
String strTrashPath = new FsPathResponseRunner<String>(op, path) {
@Override
String decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.getPath(json);
}
}.run();
return new Path(strTrashPath).makeQualified(getUri(), null);
} catch(IOException e) {
LOG.warn("Cannot find trash root of " + path, e);
// keep the same behavior with dfs
return super.getTrashRoot(path).makeQualified(getUri(), null);
}
}
@Override
public void access(final Path path, final FsAction mode) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.CHECKACCESS;
new FsPathRunner(op, path, new FsActionParam(mode)).run();
}
@Override
public ContentSummary getContentSummary(final Path p) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_CONTENT_SUMMARY);
final HttpOpParam.Op op = GetOpParam.Op.GETCONTENTSUMMARY;
return new FsPathResponseRunner<ContentSummary>(op, p) {
@Override
ContentSummary decodeResponse(Map<?,?> json) {
return JsonUtilClient.toContentSummary(json);
}
}.run();
}
@Override
public QuotaUsage getQuotaUsage(final Path p) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_QUOTA_USAGE);
final HttpOpParam.Op op = GetOpParam.Op.GETQUOTAUSAGE;
return new FsPathResponseRunner<QuotaUsage>(op, p) {
@Override
QuotaUsage decodeResponse(Map<?, ?> json) {
return JsonUtilClient.toQuotaUsage(json);
}
}.run();
}
@Override
public void setQuota(Path p, final long namespaceQuota,
final long storagespaceQuota) throws IOException {
// sanity check
if ((namespaceQuota <= 0 &&
namespaceQuota != HdfsConstants.QUOTA_RESET) ||
(storagespaceQuota < 0 &&
storagespaceQuota != HdfsConstants.QUOTA_RESET)) {
throw new IllegalArgumentException("Invalid values for quota : " +
namespaceQuota + " and " + storagespaceQuota);
}
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_QUOTA_USAGE);
final HttpOpParam.Op op = PutOpParam.Op.SETQUOTA;
new FsPathRunner(op, p, new NameSpaceQuotaParam(namespaceQuota),
new StorageSpaceQuotaParam(storagespaceQuota)).run();
}
@Override
public void setQuotaByStorageType(Path path, StorageType type, long quota)
throws IOException {
if (quota <= 0 && quota != HdfsConstants.QUOTA_RESET) {
throw new IllegalArgumentException("Invalid values for quota :" + quota);
}
if (type == null) {
throw new IllegalArgumentException("Invalid storage type (null)");
}
if (!type.supportTypeQuota()) {
throw new IllegalArgumentException(
"Quota for storage type '" + type.toString() + "' is not supported");
}
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_QUOTA_BYTSTORAGEYPE);
final HttpOpParam.Op op = PutOpParam.Op.SETQUOTABYSTORAGETYPE;
new FsPathRunner(op, path, new StorageTypeParam(type.name()),
new StorageSpaceQuotaParam(quota)).run();
}
@Override
public MD5MD5CRC32FileChecksum getFileChecksum(final Path p
) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_FILE_CHECKSUM);
final HttpOpParam.Op op = GetOpParam.Op.GETFILECHECKSUM;
return new FsPathResponseRunner<MD5MD5CRC32FileChecksum>(op, p) {
@Override
MD5MD5CRC32FileChecksum decodeResponse(Map<?,?> json) throws IOException {
return JsonUtilClient.toMD5MD5CRC32FileChecksum(json);
}
}.run();
}
/**
* Resolve an HDFS URL into real INetSocketAddress. It works like a DNS
* resolver when the URL points to an non-HA cluster. When the URL points to
* an HA cluster with its logical name, the resolver further resolves the
* logical name(i.e., the authority in the URL) into real namenode addresses.
*/
private InetSocketAddress[] resolveNNAddr() {
Configuration conf = getConf();
final String scheme = uri.getScheme();
ArrayList<InetSocketAddress> ret = new ArrayList<>();
if (!HAUtilClient.isLogicalUri(conf, uri)) {
InetSocketAddress addr = NetUtils.createSocketAddr(uri.getAuthority(),
getDefaultPort());
ret.add(addr);
} else {
Map<String, Map<String, InetSocketAddress>> addresses = DFSUtilClient
.getHaNnWebHdfsAddresses(conf, scheme);
// Extract the entry corresponding to the logical name.
Map<String, InetSocketAddress> addrs = addresses.get(uri.getHost());
for (InetSocketAddress addr : addrs.values()) {
ret.add(addr);
}
}
InetSocketAddress[] r = new InetSocketAddress[ret.size()];
return ret.toArray(r);
}
@Override
public String getCanonicalServiceName() {
return tokenServiceName == null ? super.getCanonicalServiceName()
: tokenServiceName.toString();
}
@Override
public void setStoragePolicy(Path p, String policyName) throws IOException {
if (policyName == null) {
throw new IOException("policyName == null");
}
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_STORAGE_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.SETSTORAGEPOLICY;
new FsPathRunner(op, p, new StoragePolicyParam(policyName)).run();
}
@Override
public Collection<BlockStoragePolicy> getAllStoragePolicies()
throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_STORAGE_POLICIES);
final HttpOpParam.Op op = GetOpParam.Op.GETALLSTORAGEPOLICY;
return new FsPathResponseRunner<Collection<BlockStoragePolicy>>(op, null) {
@Override
Collection<BlockStoragePolicy> decodeResponse(Map<?, ?> json)
throws IOException {
return JsonUtilClient.getStoragePolicies(json);
}
}.run();
}
@Override
public BlockStoragePolicy getStoragePolicy(Path src) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_STORAGE_POLICY);
final HttpOpParam.Op op = GetOpParam.Op.GETSTORAGEPOLICY;
return new FsPathResponseRunner<BlockStoragePolicy>(op, src) {
@Override
BlockStoragePolicy decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toBlockStoragePolicy((Map<?, ?>) json
.get(BlockStoragePolicy.class.getSimpleName()));
}
}.run();
}
@Override
public void unsetStoragePolicy(Path src) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.UNSET_STORAGE_POLICY);
final HttpOpParam.Op op = PostOpParam.Op.UNSETSTORAGEPOLICY;
new FsPathRunner(op, src).run();
}
/*
* Caller of this method should handle UnsupportedOperationException in case
* when new client is talking to old namenode that don't support
* FsServerDefaults call.
*/
@Override
public FsServerDefaults getServerDefaults() throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETSERVERDEFAULTS;
return new FsPathResponseRunner<FsServerDefaults>(op, null) {
@Override
FsServerDefaults decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toFsServerDefaults(json);
}
}.run();
}
@VisibleForTesting
InetSocketAddress[] getResolvedNNAddr() {
return nnAddrs;
}
@VisibleForTesting
public void setRetryPolicy(RetryPolicy rp) {
this.retryPolicy = rp;
}
@Override
public URI getKeyProviderUri() throws IOException {
String keyProviderUri = null;
try {
keyProviderUri = getServerDefaults().getKeyProviderUri();
} catch (UnsupportedOperationException e) {
// This means server doesn't support GETSERVERDEFAULTS call.
// Do nothing, let keyProviderUri = null.
} catch (RemoteException e) {
if (e.getClassName() != null &&
e.getClassName().equals("java.lang.IllegalArgumentException")) {
// See HDFS-13100.
// This means server doesn't support GETSERVERDEFAULTS call.
// Do nothing, let keyProviderUri = null.
} else {
throw e;
}
}
return HdfsKMSUtil.getKeyProviderUri(ugi, getUri(), keyProviderUri,
getConf());
}
@Override
public KeyProvider getKeyProvider() throws IOException {
if (testProvider != null) {
return testProvider;
}
URI keyProviderUri = getKeyProviderUri();
if (keyProviderUri == null) {
return null;
}
return KMSUtil.createKeyProviderFromUri(getConf(), keyProviderUri);
}
@VisibleForTesting
public void setTestProvider(KeyProvider kp) {
testProvider = kp;
}
/**
* HDFS client capabilities.
* Uses {@link DfsPathCapabilities} to keep in sync with HDFS.
* {@inheritDoc}
*/
@Override
public boolean hasPathCapability(final Path path, final String capability)
throws IOException {
// qualify the path to make sure that it refers to the current FS.
final Path p = makeQualified(path);
Optional<Boolean> cap = DfsPathCapabilities.hasPathCapability(p,
capability);
if (cap.isPresent()) {
return cap.get();
}
return super.hasPathCapability(p, capability);
}
/**
* This class is used for opening, reading, and seeking files while using the
* WebHdfsFileSystem. This class will invoke the retry policy when performing
* any of these actions.
*/
@VisibleForTesting
public class WebHdfsInputStream extends FSInputStream {
private ReadRunner readRunner = null;
WebHdfsInputStream(Path path, int buffersize) throws IOException {
// Only create the ReadRunner once. Each read's byte array and position
// will be updated within the ReadRunner object before every read.
readRunner = new ReadRunner(path, buffersize);
}
@Override
public int read() throws IOException {
final byte[] b = new byte[1];
return (read(b, 0, 1) == -1) ? -1 : (b[0] & 0xff);
}
@Override
public int read(byte b[], int off, int len) throws IOException {
return readRunner.read(b, off, len);
}
@Override
public void seek(long newPos) throws IOException {
readRunner.seek(newPos);
}
@Override
public long getPos() throws IOException {
return readRunner.getPos();
}
protected int getBufferSize() throws IOException {
return readRunner.getBufferSize();
}
protected Path getPath() throws IOException {
return readRunner.getPath();
}
@Override
public boolean seekToNewSource(long targetPos) throws IOException {
return false;
}
@Override
public void close() throws IOException {
readRunner.close();
}
public void setFileLength(long len) {
readRunner.setFileLength(len);
}
public long getFileLength() {
return readRunner.getFileLength();
}
@VisibleForTesting
ReadRunner getReadRunner() {
return readRunner;
}
@VisibleForTesting
void setReadRunner(ReadRunner rr) {
this.readRunner = rr;
}
FileEncryptionInfo getFileEncryptionInfo() {
return readRunner.getFileEncryptionInfo();
}
InputStream createWrappedInputStream() throws IOException {
return HdfsKMSUtil.createWrappedInputStream(
this, getKeyProvider(), getFileEncryptionInfo(), getConf());
}
}
enum RunnerState {
DISCONNECTED, // Connection is closed programmatically by ReadRunner
OPEN, // Connection has been established by ReadRunner
SEEK, // Calling code has explicitly called seek()
CLOSED // Calling code has explicitly called close()
}
/**
* This class will allow retries to occur for both open and read operations.
* The first WebHdfsFileSystem#open creates a new WebHdfsInputStream object,
* which creates a new ReadRunner object that will be used to open a
* connection and read or seek into the input stream.
*
* ReadRunner is a subclass of the AbstractRunner class, which will run the
* ReadRunner#getUrl(), ReadRunner#connect(URL), and ReadRunner#getResponse
* methods within a retry loop, based on the configured retry policy.
* ReadRunner#connect will create a connection if one has not already been
* created. Otherwise, it will return the previously created connection
* object. This is necessary because a new connection should not be created
* for every read.
* Likewise, ReadRunner#getUrl will construct a new URL object only if the
* connection has not previously been established. Otherwise, it will return
* the previously created URL object.
* ReadRunner#getResponse will initialize the input stream if it has not
* already been initialized and read the requested data from the specified
* input stream.
*/
@VisibleForTesting
protected class ReadRunner extends AbstractFsPathRunner<Integer> {
private InputStream in = null;
private HttpURLConnection cachedConnection = null;
private byte[] readBuffer;
private int readOffset;
private int readLength;
private RunnerState runnerState = RunnerState.SEEK;
private URL originalUrl = null;
private URL resolvedUrl = null;
private final Path path;
private final int bufferSize;
private long pos = 0;
private long fileLength = 0;
private FileEncryptionInfo feInfo = null;
/* The following methods are WebHdfsInputStream helpers. */
ReadRunner(Path p, int bs) throws IOException {
super(GetOpParam.Op.OPEN, p, new BufferSizeParam(bs));
this.path = p;
this.bufferSize = bs;
getRedirectedUrl();
}
private void getRedirectedUrl() throws IOException {
URLRunner urlRunner = new URLRunner(GetOpParam.Op.OPEN, null, false,
false) {
@Override
protected URL getUrl() throws IOException {
return toUrl(op, path, new BufferSizeParam(bufferSize));
}
};
HttpURLConnection conn = urlRunner.run();
String feInfoStr = conn.getHeaderField(FEFINFO_HEADER);
if (feInfoStr != null) {
Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(
feInfoStr.getBytes(StandardCharsets.UTF_8));
feInfo = PBHelperClient
.convert(FileEncryptionInfoProto.parseFrom(decodedBytes));
}
String location = conn.getHeaderField("Location");
if (location != null) {
// This saves the location for datanode where redirect was issued.
// Need to remove offset because seek can be called after open.
resolvedUrl = removeOffsetParam(new URL(location));
} else {
// This is cached for proxies like httpfsfilesystem.
cachedConnection = conn;
}
originalUrl = super.getUrl();
}
int read(byte[] b, int off, int len) throws IOException {
if (runnerState == RunnerState.CLOSED) {
throw new IOException("Stream closed");
}
if (len == 0) {
return 0;
}
// Before the first read, pos and fileLength will be 0 and readBuffer
// will all be null. They will be initialized once the first connection
// is made. Only after that it makes sense to compare pos and fileLength.
if (pos >= fileLength && readBuffer != null) {
return -1;
}
// If a seek is occurring, the input stream will have been closed, so it
// needs to be reopened. Use the URLRunner to call AbstractRunner#connect
// with the previously-cached resolved URL and with the 'redirected' flag
// set to 'true'. The resolved URL contains the URL of the previously
// opened DN as opposed to the NN. It is preferable to use the resolved
// URL when creating a connection because it does not hit the NN or every
// seek, nor does it open a connection to a new DN after every seek.
// The redirect flag is needed so that AbstractRunner#connect knows the
// URL is already resolved.
// Note that when the redirected flag is set, retries are not attempted.
// So, if the connection fails using URLRunner, clear out the connection
// and fall through to establish the connection using ReadRunner.
if (runnerState == RunnerState.SEEK) {
try {
final URL rurl = new URL(resolvedUrl + "&" + new OffsetParam(pos));
cachedConnection = new URLRunner(GetOpParam.Op.OPEN, rurl, true,
false).run();
} catch (IOException ioe) {
closeInputStream(RunnerState.DISCONNECTED);
}
}
readBuffer = b;
readOffset = off;
readLength = len;
int count = -1;
count = this.run();
if (count >= 0) {
statistics.incrementBytesRead(count);
pos += count;
} else if (pos < fileLength) {
throw new EOFException(
"Premature EOF: pos=" + pos + " < filelength=" + fileLength);
}
return count;
}
void seek(long newPos) throws IOException {
if (pos != newPos) {
pos = newPos;
closeInputStream(RunnerState.SEEK);
}
}
public void close() throws IOException {
closeInputStream(RunnerState.CLOSED);
}
/* The following methods are overriding AbstractRunner methods,
* to be called within the retry policy context by runWithRetry.
*/
@Override
protected URL getUrl() throws IOException {
// This method is called every time either a read is executed.
// The check for connection == null is to ensure that a new URL is only
// created upon a new connection and not for every read.
if (cachedConnection == null) {
// Update URL with current offset. BufferSize doesn't change, but it
// still must be included when creating the new URL.
updateURLParameters(new BufferSizeParam(bufferSize),
new OffsetParam(pos));
originalUrl = super.getUrl();
}
return originalUrl;
}
/* Only make the connection if it is not already open. Don't cache the
* connection here. After this method is called, runWithRetry will call
* validateResponse, and then call the below ReadRunner#getResponse. If
* the code path makes it that far, then we can cache the connection.
*/
@Override
protected HttpURLConnection connect(URL url) throws IOException {
HttpURLConnection conn = cachedConnection;
if (conn == null) {
try {
conn = super.connect(url);
} catch (IOException e) {
closeInputStream(RunnerState.DISCONNECTED);
throw e;
}
}
return conn;
}
/*
* This method is used to perform reads within the retry policy context.
* This code is relying on runWithRetry to always call the above connect
* method and the verifyResponse method prior to calling getResponse.
*/
@Override
Integer getResponse(final HttpURLConnection conn)
throws IOException {
try {
// In the "open-then-read" use case, runWithRetry will have executed
// ReadRunner#connect to make the connection and then executed
// validateResponse to validate the response code. Only then do we want
// to cache the connection.
// In the "read-after-seek" use case, the connection is made and the
// response is validated by the URLRunner. ReadRunner#read then caches
// the connection and the ReadRunner#connect will pass on the cached
// connection
// In either case, stream initialization is done here if necessary.
cachedConnection = conn;
if (in == null) {
in = initializeInputStream(conn);
}
int count = in.read(readBuffer, readOffset, readLength);
if (count < 0 && pos < fileLength) {
throw new EOFException(
"Premature EOF: pos=" + pos + " < filelength=" + fileLength);
}
return Integer.valueOf(count);
} catch (IOException e) {
String redirectHost = resolvedUrl.getAuthority();
if (excludeDatanodes.getValue() != null) {
excludeDatanodes = new ExcludeDatanodesParam(redirectHost + ","
+ excludeDatanodes.getValue());
} else {
excludeDatanodes = new ExcludeDatanodesParam(redirectHost);
}
// If an exception occurs, close the input stream and null it out so
// that if the abstract runner decides to retry, it will reconnect.
closeInputStream(RunnerState.DISCONNECTED);
throw e;
}
}
@VisibleForTesting
InputStream initializeInputStream(HttpURLConnection conn)
throws IOException {
// Cache the resolved URL so that it can be used in the event of
// a future seek operation.
resolvedUrl = removeOffsetParam(conn.getURL());
final String cl = conn.getHeaderField(HttpHeaders.CONTENT_LENGTH);
InputStream inStream = conn.getInputStream();
if (LOG.isDebugEnabled()) {
LOG.debug("open file: " + conn.getURL());
}
if (cl != null) {
long streamLength = Long.parseLong(cl);
fileLength = pos + streamLength;
// Java has a bug with >2GB request streams. It won't bounds check
// the reads so the transfer blocks until the server times out
inStream = new BoundedInputStream(inStream, streamLength);
} else {
fileLength = getHdfsFileStatus(path).getLen();
}
// Wrapping in BufferedInputStream because it is more performant than
// BoundedInputStream by itself.
runnerState = RunnerState.OPEN;
return new BufferedInputStream(inStream, bufferSize);
}
// Close both the InputStream and the connection.
@VisibleForTesting
void closeInputStream(RunnerState rs) throws IOException {
if (in != null) {
IOUtils.close(cachedConnection);
in = null;
}
cachedConnection = null;
runnerState = rs;
}
/* Getters and Setters */
@VisibleForTesting
protected InputStream getInputStream() {
return in;
}
@VisibleForTesting
protected void setInputStream(InputStream inStream) {
in = inStream;
}
Path getPath() {
return path;
}
int getBufferSize() {
return bufferSize;
}
long getFileLength() {
return fileLength;
}
void setFileLength(long len) {
fileLength = len;
}
long getPos() {
return pos;
}
protected FileEncryptionInfo getFileEncryptionInfo() {
return feInfo;
}
}
}
| hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.web;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_DEFAULT;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_KEY;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_KEY;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_DEFAULT;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_KEY;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.crypto.key.KeyProvider;
import org.apache.hadoop.crypto.key.KeyProviderTokenIssuer;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.CommonPathCapabilities;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.DelegationTokenRenewer;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FSInputStream;
import org.apache.hadoop.fs.FileEncryptionInfo;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.GlobalStorageStatistics;
import org.apache.hadoop.fs.GlobalStorageStatistics.StorageStatisticsProvider;
import org.apache.hadoop.fs.QuotaUsage;
import org.apache.hadoop.fs.PathCapabilities;
import org.apache.hadoop.fs.StorageStatistics;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.fs.permission.FsCreateModes;
import org.apache.hadoop.hdfs.DFSOpsCountStatistics;
import org.apache.hadoop.hdfs.DFSOpsCountStatistics.OpType;
import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.XAttrCodec;
import org.apache.hadoop.fs.XAttrSetFlag;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSUtilClient;
import org.apache.hadoop.hdfs.HAUtilClient;
import org.apache.hadoop.hdfs.HdfsKMSUtil;
import org.apache.hadoop.hdfs.client.DfsPathCapabilities;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.FileEncryptionInfoProto;
import org.apache.hadoop.hdfs.protocolPB.PBHelperClient;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.web.resources.*;
import org.apache.hadoop.hdfs.web.resources.HttpOpParam.Op;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.retry.RetryPolicies;
import org.apache.hadoop.io.retry.RetryPolicy;
import org.apache.hadoop.io.retry.RetryUtils;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.ipc.StandbyException;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.security.token.TokenSelector;
import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenSelector;
import org.apache.hadoop.security.token.DelegationTokenIssuer;
import org.apache.hadoop.util.JsonSerialization;
import org.apache.hadoop.util.KMSUtil;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import static org.apache.hadoop.fs.impl.PathCapabilitiesSupport.validatePathCapabilityArgs;
/** A FileSystem for HDFS over the web. */
public class WebHdfsFileSystem extends FileSystem
implements DelegationTokenRenewer.Renewable,
TokenAspect.TokenManagementDelegator, KeyProviderTokenIssuer {
public static final Logger LOG = LoggerFactory
.getLogger(WebHdfsFileSystem.class);
/** WebHdfs version. */
public static final int VERSION = 1;
/** Http URI: http://namenode:port/{PATH_PREFIX}/path/to/file */
public static final String PATH_PREFIX = "/" + WebHdfsConstants.WEBHDFS_SCHEME
+ "/v" + VERSION;
public static final String EZ_HEADER = "X-Hadoop-Accept-EZ";
public static final String FEFINFO_HEADER = "X-Hadoop-feInfo";
/**
* Default connection factory may be overridden in tests to use smaller
* timeout values
*/
protected URLConnectionFactory connectionFactory;
@VisibleForTesting
public static final String CANT_FALLBACK_TO_INSECURE_MSG =
"The client is configured to only allow connecting to secure cluster";
private boolean canRefreshDelegationToken;
private UserGroupInformation ugi;
private URI uri;
private Token<?> delegationToken;
protected Text tokenServiceName;
private RetryPolicy retryPolicy = null;
private Path workingDir;
private Path cachedHomeDirectory;
private InetSocketAddress nnAddrs[];
private int currentNNAddrIndex;
private boolean disallowFallbackToInsecureCluster;
private boolean isInsecureCluster;
private String restCsrfCustomHeader;
private Set<String> restCsrfMethodsToIgnore;
private DFSOpsCountStatistics storageStatistics;
private KeyProvider testProvider;
/**
* Return the protocol scheme for the FileSystem.
*
* @return <code>webhdfs</code>
*/
@Override
public String getScheme() {
return WebHdfsConstants.WEBHDFS_SCHEME;
}
/**
* return the underlying transport protocol (http / https).
*/
protected String getTransportScheme() {
return "http";
}
protected Text getTokenKind() {
return WebHdfsConstants.WEBHDFS_TOKEN_KIND;
}
@Override
public synchronized void initialize(URI uri, Configuration conf
) throws IOException {
super.initialize(uri, conf);
setConf(conf);
// set user and acl patterns based on configuration file
UserParam.setUserPattern(conf.get(
HdfsClientConfigKeys.DFS_WEBHDFS_USER_PATTERN_KEY,
HdfsClientConfigKeys.DFS_WEBHDFS_USER_PATTERN_DEFAULT));
AclPermissionParam.setAclPermissionPattern(conf.get(
HdfsClientConfigKeys.DFS_WEBHDFS_ACL_PERMISSION_PATTERN_KEY,
HdfsClientConfigKeys.DFS_WEBHDFS_ACL_PERMISSION_PATTERN_DEFAULT));
int connectTimeout = (int) conf.getTimeDuration(
HdfsClientConfigKeys.DFS_WEBHDFS_SOCKET_CONNECT_TIMEOUT_KEY,
URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT,
TimeUnit.MILLISECONDS);
int readTimeout = (int) conf.getTimeDuration(
HdfsClientConfigKeys.DFS_WEBHDFS_SOCKET_READ_TIMEOUT_KEY,
URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT,
TimeUnit.MILLISECONDS);
boolean isOAuth = conf.getBoolean(
HdfsClientConfigKeys.DFS_WEBHDFS_OAUTH_ENABLED_KEY,
HdfsClientConfigKeys.DFS_WEBHDFS_OAUTH_ENABLED_DEFAULT);
if(isOAuth) {
LOG.debug("Enabling OAuth2 in WebHDFS");
connectionFactory = URLConnectionFactory
.newOAuth2URLConnectionFactory(connectTimeout, readTimeout, conf);
} else {
LOG.debug("Not enabling OAuth2 in WebHDFS");
connectionFactory = URLConnectionFactory
.newDefaultURLConnectionFactory(connectTimeout, readTimeout, conf);
}
ugi = UserGroupInformation.getCurrentUser();
this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
this.nnAddrs = resolveNNAddr();
boolean isHA = HAUtilClient.isClientFailoverConfigured(conf, this.uri);
boolean isLogicalUri = isHA && HAUtilClient.isLogicalUri(conf, this.uri);
// In non-HA or non-logical URI case, the code needs to call
// getCanonicalUri() in order to handle the case where no port is
// specified in the URI
this.tokenServiceName = isLogicalUri ?
HAUtilClient.buildTokenServiceForLogicalUri(uri, getScheme())
: SecurityUtil.buildTokenService(getCanonicalUri());
if (!isHA) {
this.retryPolicy =
RetryUtils.getDefaultRetryPolicy(
conf,
HdfsClientConfigKeys.HttpClient.RETRY_POLICY_ENABLED_KEY,
HdfsClientConfigKeys.HttpClient.RETRY_POLICY_ENABLED_DEFAULT,
HdfsClientConfigKeys.HttpClient.RETRY_POLICY_SPEC_KEY,
HdfsClientConfigKeys.HttpClient.RETRY_POLICY_SPEC_DEFAULT,
HdfsConstants.SAFEMODE_EXCEPTION_CLASS_NAME);
} else {
int maxFailoverAttempts = conf.getInt(
HdfsClientConfigKeys.HttpClient.FAILOVER_MAX_ATTEMPTS_KEY,
HdfsClientConfigKeys.HttpClient.FAILOVER_MAX_ATTEMPTS_DEFAULT);
int maxRetryAttempts = conf.getInt(
HdfsClientConfigKeys.HttpClient.RETRY_MAX_ATTEMPTS_KEY,
HdfsClientConfigKeys.HttpClient.RETRY_MAX_ATTEMPTS_DEFAULT);
int failoverSleepBaseMillis = conf.getInt(
HdfsClientConfigKeys.HttpClient.FAILOVER_SLEEPTIME_BASE_KEY,
HdfsClientConfigKeys.HttpClient.FAILOVER_SLEEPTIME_BASE_DEFAULT);
int failoverSleepMaxMillis = conf.getInt(
HdfsClientConfigKeys.HttpClient.FAILOVER_SLEEPTIME_MAX_KEY,
HdfsClientConfigKeys.HttpClient.FAILOVER_SLEEPTIME_MAX_DEFAULT);
this.retryPolicy = RetryPolicies
.failoverOnNetworkException(RetryPolicies.TRY_ONCE_THEN_FAIL,
maxFailoverAttempts, maxRetryAttempts, failoverSleepBaseMillis,
failoverSleepMaxMillis);
}
this.workingDir = makeQualified(new Path(getHomeDirectoryString(ugi)));
this.canRefreshDelegationToken = UserGroupInformation.isSecurityEnabled();
this.isInsecureCluster = !this.canRefreshDelegationToken;
this.disallowFallbackToInsecureCluster = !conf.getBoolean(
CommonConfigurationKeys.IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY,
CommonConfigurationKeys.IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT);
this.initializeRestCsrf(conf);
this.delegationToken = null;
storageStatistics = (DFSOpsCountStatistics) GlobalStorageStatistics.INSTANCE
.put(DFSOpsCountStatistics.NAME,
new StorageStatisticsProvider() {
@Override
public StorageStatistics provide() {
return new DFSOpsCountStatistics();
}
});
}
/**
* Initializes client-side handling of cross-site request forgery (CSRF)
* protection by figuring out the custom HTTP headers that need to be sent in
* requests and which HTTP methods are ignored because they do not require
* CSRF protection.
*
* @param conf configuration to read
*/
private void initializeRestCsrf(Configuration conf) {
if (conf.getBoolean(DFS_WEBHDFS_REST_CSRF_ENABLED_KEY,
DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT)) {
this.restCsrfCustomHeader = conf.getTrimmed(
DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_KEY,
DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_DEFAULT);
this.restCsrfMethodsToIgnore = new HashSet<>();
this.restCsrfMethodsToIgnore.addAll(getTrimmedStringList(conf,
DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_KEY,
DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_DEFAULT));
} else {
this.restCsrfCustomHeader = null;
this.restCsrfMethodsToIgnore = null;
}
}
/**
* Returns a list of strings from a comma-delimited configuration value.
*
* @param conf configuration to check
* @param name configuration property name
* @param defaultValue default value if no value found for name
* @return list of strings from comma-delimited configuration value, or an
* empty list if not found
*/
private static List<String> getTrimmedStringList(Configuration conf,
String name, String defaultValue) {
String valueString = conf.get(name, defaultValue);
if (valueString == null) {
return new ArrayList<>();
}
return new ArrayList<>(StringUtils.getTrimmedStringCollection(valueString));
}
@Override
public URI getCanonicalUri() {
return super.getCanonicalUri();
}
TokenSelector<DelegationTokenIdentifier> tokenSelector =
new AbstractDelegationTokenSelector<DelegationTokenIdentifier>(getTokenKind()){};
// the first getAuthParams() for a non-token op will either get the
// internal token from the ugi or lazy fetch one
protected synchronized Token<?> getDelegationToken() throws IOException {
if (delegationToken == null) {
Token<?> token = tokenSelector.selectToken(
new Text(getCanonicalServiceName()), ugi.getTokens());
// ugi tokens are usually indicative of a task which can't
// refetch tokens. even if ugi has credentials, don't attempt
// to get another token to match hdfs/rpc behavior
if (token != null) {
LOG.debug("Using UGI token: {}", token);
canRefreshDelegationToken = false;
} else {
if (canRefreshDelegationToken) {
token = getDelegationToken(null);
if (token != null) {
LOG.debug("Fetched new token: {}", token);
} else { // security is disabled
canRefreshDelegationToken = false;
isInsecureCluster = true;
}
}
}
setDelegationToken(token);
}
return delegationToken;
}
@VisibleForTesting
synchronized boolean replaceExpiredDelegationToken() throws IOException {
boolean replaced = false;
if (canRefreshDelegationToken) {
Token<?> token = getDelegationToken(null);
LOG.debug("Replaced expired token: {}", token);
setDelegationToken(token);
replaced = (token != null);
}
return replaced;
}
@Override
protected int getDefaultPort() {
return HdfsClientConfigKeys.DFS_NAMENODE_HTTP_PORT_DEFAULT;
}
@Override
public URI getUri() {
return this.uri;
}
@Override
protected URI canonicalizeUri(URI uri) {
return NetUtils.getCanonicalUri(uri, getDefaultPort());
}
/** @return the home directory */
@Deprecated
public static String getHomeDirectoryString(final UserGroupInformation ugi) {
return "/user/" + ugi.getShortUserName();
}
@Override
public Path getHomeDirectory() {
if (cachedHomeDirectory == null) {
final HttpOpParam.Op op = GetOpParam.Op.GETHOMEDIRECTORY;
try {
String pathFromDelegatedFS = new FsPathResponseRunner<String>(op, null){
@Override
String decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.getPath(json);
}
} .run();
cachedHomeDirectory = new Path(pathFromDelegatedFS).makeQualified(
this.getUri(), null);
} catch (IOException e) {
LOG.error("Unable to get HomeDirectory from original File System", e);
cachedHomeDirectory = new Path("/user/" + ugi.getShortUserName())
.makeQualified(this.getUri(), null);
}
}
return cachedHomeDirectory;
}
@Override
public synchronized Path getWorkingDirectory() {
return workingDir;
}
@Override
public synchronized void setWorkingDirectory(final Path dir) {
Path absolutePath = makeAbsolute(dir);
String result = absolutePath.toUri().getPath();
if (!DFSUtilClient.isValidName(result)) {
throw new IllegalArgumentException("Invalid DFS directory name " +
result);
}
workingDir = absolutePath;
}
private Path makeAbsolute(Path f) {
return f.isAbsolute()? f: new Path(workingDir, f);
}
static Map<?, ?> jsonParse(final HttpURLConnection c,
final boolean useErrorStream) throws IOException {
if (c.getContentLength() == 0) {
return null;
}
final InputStream in = useErrorStream ?
c.getErrorStream() : c.getInputStream();
if (in == null) {
throw new IOException("The " + (useErrorStream? "error": "input") +
" stream is null.");
}
try {
final String contentType = c.getContentType();
if (contentType != null) {
final MediaType parsed = MediaType.valueOf(contentType);
if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
throw new IOException("Content-Type \"" + contentType
+ "\" is incompatible with \"" + MediaType.APPLICATION_JSON
+ "\" (parsed=\"" + parsed + "\")");
}
}
return JsonSerialization.mapReader().readValue(in);
} finally {
in.close();
}
}
private static Map<?, ?> validateResponse(final HttpOpParam.Op op,
final HttpURLConnection conn, boolean unwrapException)
throws IOException {
final int code = conn.getResponseCode();
// server is demanding an authentication we don't support
if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
// match hdfs/rpc exception
throw new AccessControlException(conn.getResponseMessage());
}
if (code != op.getExpectedHttpResponseCode()) {
final Map<?, ?> m;
try {
m = jsonParse(conn, true);
} catch(Exception e) {
throw new IOException("Unexpected HTTP response: code=" + code + " != "
+ op.getExpectedHttpResponseCode() + ", " + op.toQueryString()
+ ", message=" + conn.getResponseMessage(), e);
}
if (m == null) {
throw new IOException("Unexpected HTTP response: code=" + code + " != "
+ op.getExpectedHttpResponseCode() + ", " + op.toQueryString()
+ ", message=" + conn.getResponseMessage());
} else if (m.get(RemoteException.class.getSimpleName()) == null) {
return m;
}
IOException re = JsonUtilClient.toRemoteException(m);
//check if exception is due to communication with a Standby name node
if (re.getMessage() != null && re.getMessage().endsWith(
StandbyException.class.getSimpleName())) {
LOG.trace("Detected StandbyException", re);
throw new IOException(re);
}
// extract UGI-related exceptions and unwrap InvalidToken
// the NN mangles these exceptions but the DN does not and may need
// to re-fetch a token if either report the token is expired
if (re.getMessage() != null && re.getMessage().startsWith(
SecurityUtil.FAILED_TO_GET_UGI_MSG_HEADER)) {
String[] parts = re.getMessage().split(":\\s+", 3);
re = new RemoteException(parts[1], parts[2]);
re = ((RemoteException)re).unwrapRemoteException(InvalidToken.class);
}
throw unwrapException? toIOException(re): re;
}
return null;
}
/**
* Covert an exception to an IOException.
*
* For a non-IOException, wrap it with IOException.
* For a RemoteException, unwrap it.
* For an IOException which is not a RemoteException, return it.
*/
private static IOException toIOException(Exception e) {
if (!(e instanceof IOException)) {
return new IOException(e);
}
final IOException ioe = (IOException)e;
if (!(ioe instanceof RemoteException)) {
return ioe;
}
return ((RemoteException)ioe).unwrapRemoteException();
}
private synchronized InetSocketAddress getCurrentNNAddr() {
return nnAddrs[currentNNAddrIndex];
}
/**
* Reset the appropriate state to gracefully fail over to another name node
*/
private synchronized void resetStateToFailOver() {
currentNNAddrIndex = (currentNNAddrIndex + 1) % nnAddrs.length;
}
/**
* Return a URL pointing to given path on the namenode.
*
* @param path to obtain the URL for
* @param query string to append to the path
* @return namenode URL referring to the given path
* @throws IOException on error constructing the URL
*/
private URL getNamenodeURL(String path, String query) throws IOException {
InetSocketAddress nnAddr = getCurrentNNAddr();
final URL url = new URL(getTransportScheme(), nnAddr.getHostName(),
nnAddr.getPort(), path + '?' + query);
LOG.trace("url={}", url);
return url;
}
private synchronized Param<?, ?>[] getAuthParameters(final HttpOpParam.Op op)
throws IOException {
List<Param<?,?>> authParams = Lists.newArrayList();
// Skip adding delegation token for token operations because these
// operations require authentication.
Token<?> token = null;
if (!op.getRequireAuth()) {
token = getDelegationToken();
}
if (token != null) {
authParams.add(new DelegationParam(token.encodeToUrlString()));
} else {
UserGroupInformation userUgi = ugi;
UserGroupInformation realUgi = userUgi.getRealUser();
if (realUgi != null) { // proxy user
authParams.add(new DoAsParam(userUgi.getShortUserName()));
userUgi = realUgi;
}
UserParam userParam = new UserParam((userUgi.getShortUserName()));
//in insecure, use user.name parameter, in secure, use spnego auth
if(isInsecureCluster) {
authParams.add(userParam);
}
}
return authParams.toArray(new Param<?,?>[0]);
}
URL toUrl(final HttpOpParam.Op op, final Path fspath,
final Param<?,?>... parameters) throws IOException {
//initialize URI path and query
final String path = PATH_PREFIX
+ (fspath == null? "/": makeQualified(fspath).toUri().getRawPath());
final String query = op.toQueryString()
+ Param.toSortedString("&", getAuthParameters(op))
+ Param.toSortedString("&", parameters);
final URL url = getNamenodeURL(path, query);
LOG.trace("url={}", url);
return url;
}
/**
* This class is for initialing a HTTP connection, connecting to server,
* obtaining a response, and also handling retry on failures.
*/
abstract class AbstractRunner<T> {
abstract protected URL getUrl() throws IOException;
protected final HttpOpParam.Op op;
private final boolean redirected;
protected ExcludeDatanodesParam excludeDatanodes =
new ExcludeDatanodesParam("");
private boolean checkRetry;
private String redirectHost;
private boolean followRedirect = true;
protected AbstractRunner(final HttpOpParam.Op op, boolean redirected) {
this.op = op;
this.redirected = redirected;
}
protected AbstractRunner(final HttpOpParam.Op op, boolean redirected,
boolean followRedirect) {
this(op, redirected);
this.followRedirect = followRedirect;
}
T run() throws IOException {
UserGroupInformation connectUgi = ugi.getRealUser();
if (connectUgi == null) {
connectUgi = ugi;
}
if (op.getRequireAuth()) {
connectUgi.checkTGTAndReloginFromKeytab();
}
try {
// the entire lifecycle of the connection must be run inside the
// doAs to ensure authentication is performed correctly
return connectUgi.doAs(
new PrivilegedExceptionAction<T>() {
@Override
public T run() throws IOException {
return runWithRetry();
}
});
} catch (InterruptedException e) {
throw new IOException(e);
}
}
/**
* Two-step requests redirected to a DN
*
* Create/Append:
* Step 1) Submit a Http request with neither auto-redirect nor data.
* Step 2) Submit another Http request with the URL from the Location header
* with data.
*
* The reason of having two-step create/append is for preventing clients to
* send out the data before the redirect. This issue is addressed by the
* "Expect: 100-continue" header in HTTP/1.1; see RFC 2616, Section 8.2.3.
* Unfortunately, there are software library bugs (e.g. Jetty 6 http server
* and Java 6 http client), which do not correctly implement "Expect:
* 100-continue". The two-step create/append is a temporary workaround for
* the software library bugs.
*
* Open/Checksum
* Also implements two-step connects for other operations redirected to
* a DN such as open and checksum
*/
protected HttpURLConnection connect(URL url) throws IOException {
//redirect hostname and port
redirectHost = null;
// resolve redirects for a DN operation unless already resolved
if (op.getRedirect() && !redirected) {
final HttpOpParam.Op redirectOp =
HttpOpParam.TemporaryRedirectOp.valueOf(op);
final HttpURLConnection conn = connect(redirectOp, url);
// application level proxy like httpfs might not issue a redirect
if (conn.getResponseCode() == op.getExpectedHttpResponseCode()) {
return conn;
}
try {
validateResponse(redirectOp, conn, false);
url = new URL(conn.getHeaderField("Location"));
redirectHost = url.getHost() + ":" + url.getPort();
} finally {
// TODO: consider not calling conn.disconnect() to allow connection reuse
// See http://tinyurl.com/java7-http-keepalive
conn.disconnect();
}
if (!followRedirect) {
return conn;
}
}
try {
final HttpURLConnection conn = connect(op, url);
// output streams will validate on close
if (!op.getDoOutput()) {
validateResponse(op, conn, false);
}
return conn;
} catch (IOException ioe) {
if (redirectHost != null) {
if (excludeDatanodes.getValue() != null) {
excludeDatanodes = new ExcludeDatanodesParam(redirectHost + ","
+ excludeDatanodes.getValue());
} else {
excludeDatanodes = new ExcludeDatanodesParam(redirectHost);
}
}
throw ioe;
}
}
private HttpURLConnection connect(final HttpOpParam.Op op, final URL url)
throws IOException {
final HttpURLConnection conn =
(HttpURLConnection)connectionFactory.openConnection(url);
final boolean doOutput = op.getDoOutput();
conn.setRequestMethod(op.getType().toString());
conn.setInstanceFollowRedirects(false);
if (restCsrfCustomHeader != null &&
!restCsrfMethodsToIgnore.contains(op.getType().name())) {
// The value of the header is unimportant. Only its presence matters.
conn.setRequestProperty(restCsrfCustomHeader, "\"\"");
}
conn.setRequestProperty(EZ_HEADER, "true");
switch (op.getType()) {
// if not sending a message body for a POST or PUT operation, need
// to ensure the server/proxy knows this
case POST:
case PUT: {
conn.setDoOutput(true);
if (!doOutput) {
// explicitly setting content-length to 0 won't do spnego!!
// opening and closing the stream will send "Content-Length: 0"
conn.getOutputStream().close();
} else {
conn.setRequestProperty("Content-Type",
MediaType.APPLICATION_OCTET_STREAM);
conn.setChunkedStreamingMode(32 << 10); //32kB-chunk
}
break;
}
default:
conn.setDoOutput(doOutput);
break;
}
conn.connect();
return conn;
}
private T runWithRetry() throws IOException {
/**
* Do the real work.
*
* There are three cases that the code inside the loop can throw an
* IOException:
*
* <ul>
* <li>The connection has failed (e.g., ConnectException,
* @see FailoverOnNetworkExceptionRetry for more details)</li>
* <li>The namenode enters the standby state (i.e., StandbyException).</li>
* <li>The server returns errors for the command (i.e., RemoteException)</li>
* </ul>
*
* The call to shouldRetry() will conduct the retry policy. The policy
* examines the exception and swallows it if it decides to rerun the work.
*/
for(int retry = 0; ; retry++) {
checkRetry = !redirected;
final URL url = getUrl();
try {
final HttpURLConnection conn = connect(url);
return getResponse(conn);
} catch (AccessControlException ace) {
// no retries for auth failures
throw ace;
} catch (InvalidToken it) {
// try to replace the expired token with a new one. the attempt
// to acquire a new token must be outside this operation's retry
// so if it fails after its own retries, this operation fails too.
if (op.getRequireAuth() || !replaceExpiredDelegationToken()) {
throw it;
}
} catch (IOException ioe) {
// Attempt to include the redirected node in the exception. If the
// attempt to recreate the exception fails, just use the original.
String node = redirectHost;
if (node == null) {
node = url.getAuthority();
}
try {
IOException newIoe = ioe.getClass().getConstructor(String.class)
.newInstance(node + ": " + ioe.getMessage());
newIoe.initCause(ioe.getCause());
newIoe.setStackTrace(ioe.getStackTrace());
ioe = newIoe;
} catch (NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
}
shouldRetry(ioe, retry);
}
}
}
private void shouldRetry(final IOException ioe, final int retry
) throws IOException {
InetSocketAddress nnAddr = getCurrentNNAddr();
if (checkRetry) {
try {
final RetryPolicy.RetryAction a = retryPolicy.shouldRetry(
ioe, retry, 0, true);
boolean isRetry =
a.action == RetryPolicy.RetryAction.RetryDecision.RETRY;
boolean isFailoverAndRetry =
a.action == RetryPolicy.RetryAction.RetryDecision.FAILOVER_AND_RETRY;
if (isRetry || isFailoverAndRetry) {
LOG.info("Retrying connect to namenode: {}. Already retried {}"
+ " time(s); retry policy is {}, delay {}ms.",
nnAddr, retry, retryPolicy, a.delayMillis);
if (isFailoverAndRetry) {
resetStateToFailOver();
}
Thread.sleep(a.delayMillis);
return;
}
} catch(Exception e) {
LOG.warn("Original exception is ", ioe);
throw toIOException(e);
}
}
throw toIOException(ioe);
}
abstract T getResponse(HttpURLConnection conn) throws IOException;
}
/**
* Abstract base class to handle path-based operations with params
*/
abstract class AbstractFsPathRunner<T> extends AbstractRunner<T> {
private final Path fspath;
private Param<?,?>[] parameters;
AbstractFsPathRunner(final HttpOpParam.Op op, final Path fspath,
Param<?,?>... parameters) {
super(op, false);
this.fspath = fspath;
this.parameters = parameters;
}
AbstractFsPathRunner(final HttpOpParam.Op op, Param<?,?>[] parameters,
final Path fspath) {
super(op, false);
this.fspath = fspath;
this.parameters = parameters;
}
protected void updateURLParameters(Param<?, ?>... p) {
this.parameters = p;
}
@Override
protected URL getUrl() throws IOException {
if (excludeDatanodes.getValue() != null) {
Param<?, ?>[] tmpParam = new Param<?, ?>[parameters.length + 1];
System.arraycopy(parameters, 0, tmpParam, 0, parameters.length);
tmpParam[parameters.length] = excludeDatanodes;
return toUrl(op, fspath, tmpParam);
} else {
return toUrl(op, fspath, parameters);
}
}
Path getFspath() {
return fspath;
}
}
/**
* Default path-based implementation expects no json response
*/
class FsPathRunner extends AbstractFsPathRunner<Void> {
FsPathRunner(Op op, Path fspath, Param<?,?>... parameters) {
super(op, fspath, parameters);
}
@Override
Void getResponse(HttpURLConnection conn) throws IOException {
return null;
}
}
/**
* Handle path-based operations with a json response
*/
abstract class FsPathResponseRunner<T> extends AbstractFsPathRunner<T> {
FsPathResponseRunner(final HttpOpParam.Op op, final Path fspath,
Param<?,?>... parameters) {
super(op, fspath, parameters);
}
FsPathResponseRunner(final HttpOpParam.Op op, Param<?,?>[] parameters,
final Path fspath) {
super(op, parameters, fspath);
}
@Override
final T getResponse(HttpURLConnection conn) throws IOException {
try {
final Map<?,?> json = jsonParse(conn, false);
if (json == null) {
// match exception class thrown by parser
throw new IllegalStateException("Missing response");
}
return decodeResponse(json);
} catch (IOException ioe) {
throw ioe;
} catch (Exception e) { // catch json parser errors
final IOException ioe =
new IOException("Response decoding failure: "+e.toString(), e);
LOG.debug("Response decoding failure.", e);
throw ioe;
} finally {
// Don't call conn.disconnect() to allow connection reuse
// See http://tinyurl.com/java7-http-keepalive
conn.getInputStream().close();
}
}
abstract T decodeResponse(Map<?,?> json) throws IOException;
}
/**
* Handle path-based operations with json boolean response
*/
class FsPathBooleanRunner extends FsPathResponseRunner<Boolean> {
FsPathBooleanRunner(Op op, Path fspath, Param<?,?>... parameters) {
super(op, fspath, parameters);
}
@Override
Boolean decodeResponse(Map<?,?> json) throws IOException {
return (Boolean)json.get("boolean");
}
}
/**
* Handle create/append output streams
*/
class FsPathOutputStreamRunner
extends AbstractFsPathRunner<FSDataOutputStream> {
private final int bufferSize;
FsPathOutputStreamRunner(Op op, Path fspath, int bufferSize,
Param<?,?>... parameters) {
super(op, fspath, parameters);
this.bufferSize = bufferSize;
}
@Override
FSDataOutputStream getResponse(final HttpURLConnection conn)
throws IOException {
return new FSDataOutputStream(new BufferedOutputStream(
conn.getOutputStream(), bufferSize), statistics) {
@Override
public void write(int b) throws IOException {
try {
super.write(b);
} catch (IOException e) {
LOG.warn("Write to output stream for file '{}' failed. "
+ "Attempting to fetch the cause from the connection.",
getFspath(), e);
validateResponse(op, conn, true);
throw e;
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
try {
super.write(b, off, len);
} catch (IOException e) {
LOG.warn("Write to output stream for file '{}' failed. "
+ "Attempting to fetch the cause from the connection.",
getFspath(), e);
validateResponse(op, conn, true);
throw e;
}
}
@Override
public void close() throws IOException {
try {
super.close();
} finally {
try {
validateResponse(op, conn, true);
} finally {
// This is a connection to DataNode. Let's disconnect since
// there is little chance that the connection will be reused
// any time soonl
conn.disconnect();
}
}
}
};
}
}
class FsPathConnectionRunner extends AbstractFsPathRunner<HttpURLConnection> {
FsPathConnectionRunner(Op op, Path fspath, Param<?,?>... parameters) {
super(op, fspath, parameters);
}
@Override
HttpURLConnection getResponse(final HttpURLConnection conn)
throws IOException {
return conn;
}
}
/**
* Used by open() which tracks the resolved url itself
*/
class URLRunner extends AbstractRunner<HttpURLConnection> {
private final URL url;
@Override
protected URL getUrl() throws IOException {
return url;
}
protected URLRunner(final HttpOpParam.Op op, final URL url,
boolean redirected, boolean followRedirect) {
super(op, redirected, followRedirect);
this.url = url;
}
@Override
HttpURLConnection getResponse(HttpURLConnection conn) throws IOException {
return conn;
}
}
private FsPermission applyUMask(FsPermission permission) {
if (permission == null) {
permission = FsPermission.getDefault();
}
return FsCreateModes.applyUMask(permission,
FsPermission.getUMask(getConf()));
}
private HdfsFileStatus getHdfsFileStatus(Path f) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETFILESTATUS;
HdfsFileStatus status = new FsPathResponseRunner<HdfsFileStatus>(op, f) {
@Override
HdfsFileStatus decodeResponse(Map<?,?> json) {
return JsonUtilClient.toFileStatus(json, true);
}
}.run();
if (status == null) {
throw new FileNotFoundException("File does not exist: " + f);
}
return status;
}
@Override
public FileStatus getFileStatus(Path f) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_FILE_STATUS);
return getHdfsFileStatus(f).makeQualified(getUri(), f);
}
@Override
public AclStatus getAclStatus(Path f) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETACLSTATUS;
AclStatus status = new FsPathResponseRunner<AclStatus>(op, f) {
@Override
AclStatus decodeResponse(Map<?,?> json) {
return JsonUtilClient.toAclStatus(json);
}
}.run();
if (status == null) {
throw new FileNotFoundException("File does not exist: " + f);
}
return status;
}
@Override
public boolean mkdirs(Path f, FsPermission permission) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.MKDIRS);
final HttpOpParam.Op op = PutOpParam.Op.MKDIRS;
final FsPermission modes = applyUMask(permission);
return new FsPathBooleanRunner(op, f,
new PermissionParam(modes.getMasked()),
new UnmaskedPermissionParam(modes.getUnmasked())
).run();
}
@Override
public boolean supportsSymlinks() {
return true;
}
/**
* Create a symlink pointing to the destination path.
*/
public void createSymlink(Path destination, Path f, boolean createParent
) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CREATE_SYM_LINK);
final HttpOpParam.Op op = PutOpParam.Op.CREATESYMLINK;
new FsPathRunner(op, f,
new DestinationParam(makeQualified(destination).toUri().getPath()),
new CreateParentParam(createParent)
).run();
}
@Override
public boolean rename(final Path src, final Path dst) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.RENAME);
final HttpOpParam.Op op = PutOpParam.Op.RENAME;
return new FsPathBooleanRunner(op, src,
new DestinationParam(makeQualified(dst).toUri().getPath())
).run();
}
@SuppressWarnings("deprecation")
@Override
public void rename(final Path src, final Path dst,
final Options.Rename... options) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.RENAME);
final HttpOpParam.Op op = PutOpParam.Op.RENAME;
new FsPathRunner(op, src,
new DestinationParam(makeQualified(dst).toUri().getPath()),
new RenameOptionSetParam(options)
).run();
}
@Override
public void setXAttr(Path p, String name, byte[] value,
EnumSet<XAttrSetFlag> flag) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_XATTR);
final HttpOpParam.Op op = PutOpParam.Op.SETXATTR;
if (value != null) {
new FsPathRunner(op, p, new XAttrNameParam(name), new XAttrValueParam(
XAttrCodec.encodeValue(value, XAttrCodec.HEX)),
new XAttrSetFlagParam(flag)).run();
} else {
new FsPathRunner(op, p, new XAttrNameParam(name),
new XAttrSetFlagParam(flag)).run();
}
}
@Override
public byte[] getXAttr(Path p, final String name) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_XATTR);
final HttpOpParam.Op op = GetOpParam.Op.GETXATTRS;
return new FsPathResponseRunner<byte[]>(op, p, new XAttrNameParam(name),
new XAttrEncodingParam(XAttrCodec.HEX)) {
@Override
byte[] decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.getXAttr(json);
}
}.run();
}
@Override
public Map<String, byte[]> getXAttrs(Path p) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETXATTRS;
return new FsPathResponseRunner<Map<String, byte[]>>(op, p,
new XAttrEncodingParam(XAttrCodec.HEX)) {
@Override
Map<String, byte[]> decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toXAttrs(json);
}
}.run();
}
@Override
public Map<String, byte[]> getXAttrs(Path p, final List<String> names)
throws IOException {
Preconditions.checkArgument(names != null && !names.isEmpty(),
"XAttr names cannot be null or empty.");
Param<?,?>[] parameters = new Param<?,?>[names.size() + 1];
for (int i = 0; i < parameters.length - 1; i++) {
parameters[i] = new XAttrNameParam(names.get(i));
}
parameters[parameters.length - 1] = new XAttrEncodingParam(XAttrCodec.HEX);
final HttpOpParam.Op op = GetOpParam.Op.GETXATTRS;
return new FsPathResponseRunner<Map<String, byte[]>>(op, parameters, p) {
@Override
Map<String, byte[]> decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toXAttrs(json);
}
}.run();
}
@Override
public List<String> listXAttrs(Path p) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.LISTXATTRS;
return new FsPathResponseRunner<List<String>>(op, p) {
@Override
List<String> decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toXAttrNames(json);
}
}.run();
}
@Override
public void removeXAttr(Path p, String name) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.REMOVE_XATTR);
final HttpOpParam.Op op = PutOpParam.Op.REMOVEXATTR;
new FsPathRunner(op, p, new XAttrNameParam(name)).run();
}
@Override
public void setOwner(final Path p, final String owner, final String group
) throws IOException {
if (owner == null && group == null) {
throw new IOException("owner == null && group == null");
}
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_OWNER);
final HttpOpParam.Op op = PutOpParam.Op.SETOWNER;
new FsPathRunner(op, p,
new OwnerParam(owner), new GroupParam(group)
).run();
}
@Override
public void setPermission(final Path p, final FsPermission permission
) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_PERMISSION);
final HttpOpParam.Op op = PutOpParam.Op.SETPERMISSION;
new FsPathRunner(op, p,new PermissionParam(permission)).run();
}
@Override
public void modifyAclEntries(Path path, List<AclEntry> aclSpec)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.MODIFY_ACL_ENTRIES);
final HttpOpParam.Op op = PutOpParam.Op.MODIFYACLENTRIES;
new FsPathRunner(op, path, new AclPermissionParam(aclSpec)).run();
}
@Override
public void removeAclEntries(Path path, List<AclEntry> aclSpec)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.REMOVE_ACL_ENTRIES);
final HttpOpParam.Op op = PutOpParam.Op.REMOVEACLENTRIES;
new FsPathRunner(op, path, new AclPermissionParam(aclSpec)).run();
}
@Override
public void removeDefaultAcl(Path path) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.REMOVE_DEFAULT_ACL);
final HttpOpParam.Op op = PutOpParam.Op.REMOVEDEFAULTACL;
new FsPathRunner(op, path).run();
}
@Override
public void removeAcl(Path path) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.REMOVE_ACL);
final HttpOpParam.Op op = PutOpParam.Op.REMOVEACL;
new FsPathRunner(op, path).run();
}
@Override
public void setAcl(final Path p, final List<AclEntry> aclSpec)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_ACL);
final HttpOpParam.Op op = PutOpParam.Op.SETACL;
new FsPathRunner(op, p, new AclPermissionParam(aclSpec)).run();
}
public void allowSnapshot(final Path p) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.ALLOW_SNAPSHOT);
final HttpOpParam.Op op = PutOpParam.Op.ALLOWSNAPSHOT;
new FsPathRunner(op, p).run();
}
@Override
public void satisfyStoragePolicy(final Path p) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SATISFY_STORAGE_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.SATISFYSTORAGEPOLICY;
new FsPathRunner(op, p).run();
}
public void enableECPolicy(String policyName) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.ENABLE_EC_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.ENABLEECPOLICY;
new FsPathRunner(op, null, new ECPolicyParam(policyName)).run();
}
public void disableECPolicy(String policyName) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.DISABLE_EC_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.DISABLEECPOLICY;
new FsPathRunner(op, null, new ECPolicyParam(policyName)).run();
}
public void setErasureCodingPolicy(Path p, String policyName)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_EC_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.SETECPOLICY;
new FsPathRunner(op, p, new ECPolicyParam(policyName)).run();
}
public void unsetErasureCodingPolicy(Path p) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.UNSET_EC_POLICY);
final HttpOpParam.Op op = PostOpParam.Op.UNSETECPOLICY;
new FsPathRunner(op, p).run();
}
public ErasureCodingPolicy getErasureCodingPolicy(Path p)
throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_EC_POLICY);
final HttpOpParam.Op op =GetOpParam.Op.GETECPOLICY;
return new FsPathResponseRunner<ErasureCodingPolicy>(op, p) {
@Override
ErasureCodingPolicy decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toECPolicy((Map<?, ?>) json);
}
}.run();
}
@Override
public Path createSnapshot(final Path path, final String snapshotName)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CREATE_SNAPSHOT);
final HttpOpParam.Op op = PutOpParam.Op.CREATESNAPSHOT;
return new FsPathResponseRunner<Path>(op, path,
new SnapshotNameParam(snapshotName)) {
@Override
Path decodeResponse(Map<?,?> json) {
return new Path((String) json.get(Path.class.getSimpleName()));
}
}.run();
}
public void disallowSnapshot(final Path p) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.DISALLOW_SNAPSHOT);
final HttpOpParam.Op op = PutOpParam.Op.DISALLOWSNAPSHOT;
new FsPathRunner(op, p).run();
}
@Override
public void deleteSnapshot(final Path path, final String snapshotName)
throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.DELETE_SNAPSHOT);
final HttpOpParam.Op op = DeleteOpParam.Op.DELETESNAPSHOT;
new FsPathRunner(op, path, new SnapshotNameParam(snapshotName)).run();
}
@Override
public void renameSnapshot(final Path path, final String snapshotOldName,
final String snapshotNewName) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.RENAME_SNAPSHOT);
final HttpOpParam.Op op = PutOpParam.Op.RENAMESNAPSHOT;
new FsPathRunner(op, path, new OldSnapshotNameParam(snapshotOldName),
new SnapshotNameParam(snapshotNewName)).run();
}
public SnapshotDiffReport getSnapshotDiffReport(final Path snapshotDir,
final String fromSnapshot, final String toSnapshot) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_SNAPSHOT_DIFF);
final HttpOpParam.Op op = GetOpParam.Op.GETSNAPSHOTDIFF;
return new FsPathResponseRunner<SnapshotDiffReport>(op, snapshotDir,
new OldSnapshotNameParam(fromSnapshot),
new SnapshotNameParam(toSnapshot)) {
@Override
SnapshotDiffReport decodeResponse(Map<?, ?> json) {
return JsonUtilClient.toSnapshotDiffReport(json);
}
}.run();
}
public SnapshottableDirectoryStatus[] getSnapshottableDirectoryList()
throws IOException {
statistics.incrementReadOps(1);
storageStatistics
.incrementOpCounter(OpType.GET_SNAPSHOTTABLE_DIRECTORY_LIST);
final HttpOpParam.Op op = GetOpParam.Op.GETSNAPSHOTTABLEDIRECTORYLIST;
return new FsPathResponseRunner<SnapshottableDirectoryStatus[]>(op, null) {
@Override
SnapshottableDirectoryStatus[] decodeResponse(Map<?, ?> json) {
return JsonUtilClient.toSnapshottableDirectoryList(json);
}
}.run();
}
@Override
public boolean setReplication(final Path p, final short replication
) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_REPLICATION);
final HttpOpParam.Op op = PutOpParam.Op.SETREPLICATION;
return new FsPathBooleanRunner(op, p,
new ReplicationParam(replication)
).run();
}
@Override
public void setTimes(final Path p, final long mtime, final long atime
) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_TIMES);
final HttpOpParam.Op op = PutOpParam.Op.SETTIMES;
new FsPathRunner(op, p,
new ModificationTimeParam(mtime),
new AccessTimeParam(atime)
).run();
}
@Override
public long getDefaultBlockSize() {
return getConf().getLongBytes(HdfsClientConfigKeys.DFS_BLOCK_SIZE_KEY,
HdfsClientConfigKeys.DFS_BLOCK_SIZE_DEFAULT);
}
@Override
public short getDefaultReplication() {
return (short)getConf().getInt(HdfsClientConfigKeys.DFS_REPLICATION_KEY,
HdfsClientConfigKeys.DFS_REPLICATION_DEFAULT);
}
@Override
public void concat(final Path trg, final Path [] srcs) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CONCAT);
final HttpOpParam.Op op = PostOpParam.Op.CONCAT;
new FsPathRunner(op, trg, new ConcatSourcesParam(srcs)).run();
}
@Override
public FSDataOutputStream create(final Path f, final FsPermission permission,
final boolean overwrite, final int bufferSize, final short replication,
final long blockSize, final Progressable progress) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CREATE);
final FsPermission modes = applyUMask(permission);
final HttpOpParam.Op op = PutOpParam.Op.CREATE;
return new FsPathOutputStreamRunner(op, f, bufferSize,
new PermissionParam(modes.getMasked()),
new UnmaskedPermissionParam(modes.getUnmasked()),
new OverwriteParam(overwrite),
new BufferSizeParam(bufferSize),
new ReplicationParam(replication),
new BlockSizeParam(blockSize)
).run();
}
@Override
public FSDataOutputStream createNonRecursive(final Path f,
final FsPermission permission, final EnumSet<CreateFlag> flag,
final int bufferSize, final short replication, final long blockSize,
final Progressable progress) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.CREATE_NON_RECURSIVE);
final FsPermission modes = applyUMask(permission);
final HttpOpParam.Op op = PutOpParam.Op.CREATE;
return new FsPathOutputStreamRunner(op, f, bufferSize,
new PermissionParam(modes.getMasked()),
new UnmaskedPermissionParam(modes.getUnmasked()),
new CreateFlagParam(flag),
new CreateParentParam(false),
new BufferSizeParam(bufferSize),
new ReplicationParam(replication),
new BlockSizeParam(blockSize)
).run();
}
@Override
public FSDataOutputStream append(final Path f, final int bufferSize,
final Progressable progress) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.APPEND);
final HttpOpParam.Op op = PostOpParam.Op.APPEND;
return new FsPathOutputStreamRunner(op, f, bufferSize,
new BufferSizeParam(bufferSize)
).run();
}
@Override
public boolean truncate(Path f, long newLength) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.TRUNCATE);
final HttpOpParam.Op op = PostOpParam.Op.TRUNCATE;
return new FsPathBooleanRunner(op, f, new NewLengthParam(newLength)).run();
}
@Override
public boolean delete(Path f, boolean recursive) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.DELETE);
final HttpOpParam.Op op = DeleteOpParam.Op.DELETE;
return new FsPathBooleanRunner(op, f,
new RecursiveParam(recursive)
).run();
}
@SuppressWarnings("resource")
@Override
public FSDataInputStream open(final Path f, final int bufferSize
) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.OPEN);
WebHdfsInputStream webfsInputStream =
new WebHdfsInputStream(f, bufferSize);
if (webfsInputStream.getFileEncryptionInfo() == null) {
return new FSDataInputStream(webfsInputStream);
} else {
return new FSDataInputStream(
webfsInputStream.createWrappedInputStream());
}
}
@Override
public synchronized void close() throws IOException {
try {
if (canRefreshDelegationToken && delegationToken != null) {
cancelDelegationToken(delegationToken);
}
} catch (IOException ioe) {
LOG.debug("Token cancel failed: ", ioe);
} finally {
if (connectionFactory != null) {
connectionFactory.destroy();
}
super.close();
}
}
// use FsPathConnectionRunner to ensure retries for InvalidTokens
class UnresolvedUrlOpener extends ByteRangeInputStream.URLOpener {
private final FsPathConnectionRunner runner;
UnresolvedUrlOpener(FsPathConnectionRunner runner) {
super(null);
this.runner = runner;
}
@Override
protected HttpURLConnection connect(long offset, boolean resolved)
throws IOException {
assert offset == 0;
HttpURLConnection conn = runner.run();
setURL(conn.getURL());
return conn;
}
}
class OffsetUrlOpener extends ByteRangeInputStream.URLOpener {
OffsetUrlOpener(final URL url) {
super(url);
}
/** Setup offset url and connect. */
@Override
protected HttpURLConnection connect(final long offset,
final boolean resolved) throws IOException {
final URL offsetUrl = offset == 0L? url
: new URL(url + "&" + new OffsetParam(offset));
return new URLRunner(GetOpParam.Op.OPEN, offsetUrl, resolved,
true).run();
}
}
private static final String OFFSET_PARAM_PREFIX = OffsetParam.NAME + "=";
/** Remove offset parameter, if there is any, from the url */
static URL removeOffsetParam(final URL url) throws MalformedURLException {
String query = url.getQuery();
if (query == null) {
return url;
}
final String lower = StringUtils.toLowerCase(query);
if (!lower.startsWith(OFFSET_PARAM_PREFIX)
&& !lower.contains("&" + OFFSET_PARAM_PREFIX)) {
return url;
}
//rebuild query
StringBuilder b = null;
for(final StringTokenizer st = new StringTokenizer(query, "&");
st.hasMoreTokens();) {
final String token = st.nextToken();
if (!StringUtils.toLowerCase(token).startsWith(OFFSET_PARAM_PREFIX)) {
if (b == null) {
b = new StringBuilder("?").append(token);
} else {
b.append('&').append(token);
}
}
}
query = b == null? "": b.toString();
final String urlStr = url.toString();
return new URL(urlStr.substring(0, urlStr.indexOf('?')) + query);
}
static class OffsetUrlInputStream extends ByteRangeInputStream {
OffsetUrlInputStream(UnresolvedUrlOpener o, OffsetUrlOpener r)
throws IOException {
super(o, r);
}
/** Remove offset parameter before returning the resolved url. */
@Override
protected URL getResolvedUrl(final HttpURLConnection connection
) throws MalformedURLException {
return removeOffsetParam(connection.getURL());
}
}
/**
* Get {@link FileStatus} of files/directories in the given path. If path
* corresponds to a file then {@link FileStatus} of that file is returned.
* Else if path represents a directory then {@link FileStatus} of all
* files/directories inside given path is returned.
*
* @param f given path
* @return the statuses of the files/directories in the given path
*/
@Override
public FileStatus[] listStatus(final Path f) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.LIST_STATUS);
final URI fsUri = getUri();
final HttpOpParam.Op op = GetOpParam.Op.LISTSTATUS;
return new FsPathResponseRunner<FileStatus[]>(op, f) {
@Override
FileStatus[] decodeResponse(Map<?,?> json) {
HdfsFileStatus[] hdfsStatuses =
JsonUtilClient.toHdfsFileStatusArray(json);
final FileStatus[] statuses = new FileStatus[hdfsStatuses.length];
for (int i = 0; i < hdfsStatuses.length; i++) {
statuses[i] = hdfsStatuses[i].makeQualified(fsUri, f);
}
return statuses;
}
}.run();
}
private static final byte[] EMPTY_ARRAY = new byte[] {};
/**
* Get DirectoryEntries of the given path. DirectoryEntries contains an array
* of {@link FileStatus}, as well as iteration information.
*
* @param f given path
* @return DirectoryEntries for given path
*/
@Override
public DirectoryEntries listStatusBatch(Path f, byte[] token) throws
FileNotFoundException, IOException {
byte[] prevKey = EMPTY_ARRAY;
if (token != null) {
prevKey = token;
}
DirectoryListing listing = new FsPathResponseRunner<DirectoryListing>(
GetOpParam.Op.LISTSTATUS_BATCH,
f, new StartAfterParam(new String(prevKey, Charsets.UTF_8))) {
@Override
DirectoryListing decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toDirectoryListing(json);
}
}.run();
// Qualify the returned FileStatus array
final URI fsUri = getUri();
final HdfsFileStatus[] statuses = listing.getPartialListing();
FileStatus[] qualified = new FileStatus[statuses.length];
for (int i = 0; i < statuses.length; i++) {
qualified[i] = statuses[i].makeQualified(fsUri, f);
}
return new DirectoryEntries(qualified, listing.getLastName(),
listing.hasMore());
}
@Override
public Token<DelegationTokenIdentifier> getDelegationToken(
final String renewer) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETDELEGATIONTOKEN;
Token<DelegationTokenIdentifier> token =
new FsPathResponseRunner<Token<DelegationTokenIdentifier>>(
op, null, new RenewerParam(renewer)) {
@Override
Token<DelegationTokenIdentifier> decodeResponse(Map<?,?> json)
throws IOException {
return JsonUtilClient.toDelegationToken(json);
}
}.run();
if (token != null) {
token.setService(tokenServiceName);
} else {
if (disallowFallbackToInsecureCluster) {
throw new AccessControlException(CANT_FALLBACK_TO_INSECURE_MSG);
}
}
return token;
}
@Override
public DelegationTokenIssuer[] getAdditionalTokenIssuers()
throws IOException {
KeyProvider keyProvider = getKeyProvider();
if (keyProvider instanceof DelegationTokenIssuer) {
return new DelegationTokenIssuer[] {(DelegationTokenIssuer) keyProvider};
}
return null;
}
@Override
public synchronized Token<?> getRenewToken() {
return delegationToken;
}
@Override
public <T extends TokenIdentifier> void setDelegationToken(
final Token<T> token) {
synchronized (this) {
delegationToken = token;
}
}
@Override
public synchronized long renewDelegationToken(final Token<?> token
) throws IOException {
final HttpOpParam.Op op = PutOpParam.Op.RENEWDELEGATIONTOKEN;
return new FsPathResponseRunner<Long>(op, null,
new TokenArgumentParam(token.encodeToUrlString())) {
@Override
Long decodeResponse(Map<?,?> json) throws IOException {
return ((Number) json.get("long")).longValue();
}
}.run();
}
@Override
public synchronized void cancelDelegationToken(final Token<?> token
) throws IOException {
final HttpOpParam.Op op = PutOpParam.Op.CANCELDELEGATIONTOKEN;
new FsPathRunner(op, null,
new TokenArgumentParam(token.encodeToUrlString())
).run();
}
public BlockLocation[] getFileBlockLocations(final FileStatus status,
final long offset, final long length) throws IOException {
if (status == null) {
return null;
}
return getFileBlockLocations(status.getPath(), offset, length);
}
@Override
public BlockLocation[] getFileBlockLocations(final Path p,
final long offset, final long length) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_FILE_BLOCK_LOCATIONS);
final HttpOpParam.Op op = GetOpParam.Op.GET_BLOCK_LOCATIONS;
return new FsPathResponseRunner<BlockLocation[]>(op, p,
new OffsetParam(offset), new LengthParam(length)) {
@Override
BlockLocation[] decodeResponse(Map<?,?> json) throws IOException {
return DFSUtilClient.locatedBlocks2Locations(
JsonUtilClient.toLocatedBlocks(json));
}
}.run();
}
@Override
public Path getTrashRoot(Path path) {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_TRASH_ROOT);
final HttpOpParam.Op op = GetOpParam.Op.GETTRASHROOT;
try {
String strTrashPath = new FsPathResponseRunner<String>(op, path) {
@Override
String decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.getPath(json);
}
}.run();
return new Path(strTrashPath).makeQualified(getUri(), null);
} catch(IOException e) {
LOG.warn("Cannot find trash root of " + path, e);
// keep the same behavior with dfs
return super.getTrashRoot(path).makeQualified(getUri(), null);
}
}
@Override
public void access(final Path path, final FsAction mode) throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.CHECKACCESS;
new FsPathRunner(op, path, new FsActionParam(mode)).run();
}
@Override
public ContentSummary getContentSummary(final Path p) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_CONTENT_SUMMARY);
final HttpOpParam.Op op = GetOpParam.Op.GETCONTENTSUMMARY;
return new FsPathResponseRunner<ContentSummary>(op, p) {
@Override
ContentSummary decodeResponse(Map<?,?> json) {
return JsonUtilClient.toContentSummary(json);
}
}.run();
}
@Override
public QuotaUsage getQuotaUsage(final Path p) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_QUOTA_USAGE);
final HttpOpParam.Op op = GetOpParam.Op.GETQUOTAUSAGE;
return new FsPathResponseRunner<QuotaUsage>(op, p) {
@Override
QuotaUsage decodeResponse(Map<?, ?> json) {
return JsonUtilClient.toQuotaUsage(json);
}
}.run();
}
@Override
public void setQuota(Path p, final long namespaceQuota,
final long storagespaceQuota) throws IOException {
// sanity check
if ((namespaceQuota <= 0 &&
namespaceQuota != HdfsConstants.QUOTA_RESET) ||
(storagespaceQuota < 0 &&
storagespaceQuota != HdfsConstants.QUOTA_RESET)) {
throw new IllegalArgumentException("Invalid values for quota : " +
namespaceQuota + " and " + storagespaceQuota);
}
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_QUOTA_USAGE);
final HttpOpParam.Op op = PutOpParam.Op.SETQUOTA;
new FsPathRunner(op, p, new NameSpaceQuotaParam(namespaceQuota),
new StorageSpaceQuotaParam(storagespaceQuota)).run();
}
@Override
public void setQuotaByStorageType(Path path, StorageType type, long quota)
throws IOException {
if (quota <= 0 && quota != HdfsConstants.QUOTA_RESET) {
throw new IllegalArgumentException("Invalid values for quota :" + quota);
}
if (type == null) {
throw new IllegalArgumentException("Invalid storage type (null)");
}
if (!type.supportTypeQuota()) {
throw new IllegalArgumentException(
"Quota for storage type '" + type.toString() + "' is not supported");
}
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_QUOTA_BYTSTORAGEYPE);
final HttpOpParam.Op op = PutOpParam.Op.SETQUOTABYSTORAGETYPE;
new FsPathRunner(op, path, new StorageTypeParam(type.name()),
new StorageSpaceQuotaParam(quota)).run();
}
@Override
public MD5MD5CRC32FileChecksum getFileChecksum(final Path p
) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_FILE_CHECKSUM);
final HttpOpParam.Op op = GetOpParam.Op.GETFILECHECKSUM;
return new FsPathResponseRunner<MD5MD5CRC32FileChecksum>(op, p) {
@Override
MD5MD5CRC32FileChecksum decodeResponse(Map<?,?> json) throws IOException {
return JsonUtilClient.toMD5MD5CRC32FileChecksum(json);
}
}.run();
}
/**
* Resolve an HDFS URL into real INetSocketAddress. It works like a DNS
* resolver when the URL points to an non-HA cluster. When the URL points to
* an HA cluster with its logical name, the resolver further resolves the
* logical name(i.e., the authority in the URL) into real namenode addresses.
*/
private InetSocketAddress[] resolveNNAddr() {
Configuration conf = getConf();
final String scheme = uri.getScheme();
ArrayList<InetSocketAddress> ret = new ArrayList<>();
if (!HAUtilClient.isLogicalUri(conf, uri)) {
InetSocketAddress addr = NetUtils.createSocketAddr(uri.getAuthority(),
getDefaultPort());
ret.add(addr);
} else {
Map<String, Map<String, InetSocketAddress>> addresses = DFSUtilClient
.getHaNnWebHdfsAddresses(conf, scheme);
// Extract the entry corresponding to the logical name.
Map<String, InetSocketAddress> addrs = addresses.get(uri.getHost());
for (InetSocketAddress addr : addrs.values()) {
ret.add(addr);
}
}
InetSocketAddress[] r = new InetSocketAddress[ret.size()];
return ret.toArray(r);
}
@Override
public String getCanonicalServiceName() {
return tokenServiceName == null ? super.getCanonicalServiceName()
: tokenServiceName.toString();
}
@Override
public void setStoragePolicy(Path p, String policyName) throws IOException {
if (policyName == null) {
throw new IOException("policyName == null");
}
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.SET_STORAGE_POLICY);
final HttpOpParam.Op op = PutOpParam.Op.SETSTORAGEPOLICY;
new FsPathRunner(op, p, new StoragePolicyParam(policyName)).run();
}
@Override
public Collection<BlockStoragePolicy> getAllStoragePolicies()
throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_STORAGE_POLICIES);
final HttpOpParam.Op op = GetOpParam.Op.GETALLSTORAGEPOLICY;
return new FsPathResponseRunner<Collection<BlockStoragePolicy>>(op, null) {
@Override
Collection<BlockStoragePolicy> decodeResponse(Map<?, ?> json)
throws IOException {
return JsonUtilClient.getStoragePolicies(json);
}
}.run();
}
@Override
public BlockStoragePolicy getStoragePolicy(Path src) throws IOException {
statistics.incrementReadOps(1);
storageStatistics.incrementOpCounter(OpType.GET_STORAGE_POLICY);
final HttpOpParam.Op op = GetOpParam.Op.GETSTORAGEPOLICY;
return new FsPathResponseRunner<BlockStoragePolicy>(op, src) {
@Override
BlockStoragePolicy decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toBlockStoragePolicy((Map<?, ?>) json
.get(BlockStoragePolicy.class.getSimpleName()));
}
}.run();
}
@Override
public void unsetStoragePolicy(Path src) throws IOException {
statistics.incrementWriteOps(1);
storageStatistics.incrementOpCounter(OpType.UNSET_STORAGE_POLICY);
final HttpOpParam.Op op = PostOpParam.Op.UNSETSTORAGEPOLICY;
new FsPathRunner(op, src).run();
}
/*
* Caller of this method should handle UnsupportedOperationException in case
* when new client is talking to old namenode that don't support
* FsServerDefaults call.
*/
@Override
public FsServerDefaults getServerDefaults() throws IOException {
final HttpOpParam.Op op = GetOpParam.Op.GETSERVERDEFAULTS;
return new FsPathResponseRunner<FsServerDefaults>(op, null) {
@Override
FsServerDefaults decodeResponse(Map<?, ?> json) throws IOException {
return JsonUtilClient.toFsServerDefaults(json);
}
}.run();
}
@VisibleForTesting
InetSocketAddress[] getResolvedNNAddr() {
return nnAddrs;
}
@VisibleForTesting
public void setRetryPolicy(RetryPolicy rp) {
this.retryPolicy = rp;
}
@Override
public URI getKeyProviderUri() throws IOException {
String keyProviderUri = null;
try {
keyProviderUri = getServerDefaults().getKeyProviderUri();
} catch (UnsupportedOperationException e) {
// This means server doesn't support GETSERVERDEFAULTS call.
// Do nothing, let keyProviderUri = null.
} catch (RemoteException e) {
if (e.getClassName() != null &&
e.getClassName().equals("java.lang.IllegalArgumentException")) {
// See HDFS-13100.
// This means server doesn't support GETSERVERDEFAULTS call.
// Do nothing, let keyProviderUri = null.
} else {
throw e;
}
}
return HdfsKMSUtil.getKeyProviderUri(ugi, getUri(), keyProviderUri,
getConf());
}
@Override
public KeyProvider getKeyProvider() throws IOException {
if (testProvider != null) {
return testProvider;
}
URI keyProviderUri = getKeyProviderUri();
if (keyProviderUri == null) {
return null;
}
return KMSUtil.createKeyProviderFromUri(getConf(), keyProviderUri);
}
@VisibleForTesting
public void setTestProvider(KeyProvider kp) {
testProvider = kp;
}
/**
* HDFS client capabilities.
* Uses {@link DfsPathCapabilities} to keep in sync with HDFS.
* {@inheritDoc}
*/
@Override
public boolean hasPathCapability(final Path path, final String capability)
throws IOException {
// qualify the path to make sure that it refers to the current FS.
final Path p = makeQualified(path);
Optional<Boolean> cap = DfsPathCapabilities.hasPathCapability(p,
capability);
if (cap.isPresent()) {
return cap.get();
}
return super.hasPathCapability(p, capability);
}
/**
* This class is used for opening, reading, and seeking files while using the
* WebHdfsFileSystem. This class will invoke the retry policy when performing
* any of these actions.
*/
@VisibleForTesting
public class WebHdfsInputStream extends FSInputStream {
private ReadRunner readRunner = null;
WebHdfsInputStream(Path path, int buffersize) throws IOException {
// Only create the ReadRunner once. Each read's byte array and position
// will be updated within the ReadRunner object before every read.
readRunner = new ReadRunner(path, buffersize);
}
@Override
public int read() throws IOException {
final byte[] b = new byte[1];
return (read(b, 0, 1) == -1) ? -1 : (b[0] & 0xff);
}
@Override
public int read(byte b[], int off, int len) throws IOException {
return readRunner.read(b, off, len);
}
@Override
public void seek(long newPos) throws IOException {
readRunner.seek(newPos);
}
@Override
public long getPos() throws IOException {
return readRunner.getPos();
}
protected int getBufferSize() throws IOException {
return readRunner.getBufferSize();
}
protected Path getPath() throws IOException {
return readRunner.getPath();
}
@Override
public boolean seekToNewSource(long targetPos) throws IOException {
return false;
}
@Override
public void close() throws IOException {
readRunner.close();
}
public void setFileLength(long len) {
readRunner.setFileLength(len);
}
public long getFileLength() {
return readRunner.getFileLength();
}
@VisibleForTesting
ReadRunner getReadRunner() {
return readRunner;
}
@VisibleForTesting
void setReadRunner(ReadRunner rr) {
this.readRunner = rr;
}
FileEncryptionInfo getFileEncryptionInfo() {
return readRunner.getFileEncryptionInfo();
}
InputStream createWrappedInputStream() throws IOException {
return HdfsKMSUtil.createWrappedInputStream(
this, getKeyProvider(), getFileEncryptionInfo(), getConf());
}
}
enum RunnerState {
DISCONNECTED, // Connection is closed programmatically by ReadRunner
OPEN, // Connection has been established by ReadRunner
SEEK, // Calling code has explicitly called seek()
CLOSED // Calling code has explicitly called close()
}
/**
* This class will allow retries to occur for both open and read operations.
* The first WebHdfsFileSystem#open creates a new WebHdfsInputStream object,
* which creates a new ReadRunner object that will be used to open a
* connection and read or seek into the input stream.
*
* ReadRunner is a subclass of the AbstractRunner class, which will run the
* ReadRunner#getUrl(), ReadRunner#connect(URL), and ReadRunner#getResponse
* methods within a retry loop, based on the configured retry policy.
* ReadRunner#connect will create a connection if one has not already been
* created. Otherwise, it will return the previously created connection
* object. This is necessary because a new connection should not be created
* for every read.
* Likewise, ReadRunner#getUrl will construct a new URL object only if the
* connection has not previously been established. Otherwise, it will return
* the previously created URL object.
* ReadRunner#getResponse will initialize the input stream if it has not
* already been initialized and read the requested data from the specified
* input stream.
*/
@VisibleForTesting
protected class ReadRunner extends AbstractFsPathRunner<Integer> {
private InputStream in = null;
private HttpURLConnection cachedConnection = null;
private byte[] readBuffer;
private int readOffset;
private int readLength;
private RunnerState runnerState = RunnerState.SEEK;
private URL originalUrl = null;
private URL resolvedUrl = null;
private final Path path;
private final int bufferSize;
private long pos = 0;
private long fileLength = 0;
private FileEncryptionInfo feInfo = null;
/* The following methods are WebHdfsInputStream helpers. */
ReadRunner(Path p, int bs) throws IOException {
super(GetOpParam.Op.OPEN, p, new BufferSizeParam(bs));
this.path = p;
this.bufferSize = bs;
getRedirectedUrl();
}
private void getRedirectedUrl() throws IOException {
URLRunner urlRunner = new URLRunner(GetOpParam.Op.OPEN, null, false,
false) {
@Override
protected URL getUrl() throws IOException {
return toUrl(op, path, new BufferSizeParam(bufferSize));
}
};
HttpURLConnection conn = urlRunner.run();
String feInfoStr = conn.getHeaderField(FEFINFO_HEADER);
if (feInfoStr != null) {
Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(
feInfoStr.getBytes(StandardCharsets.UTF_8));
feInfo = PBHelperClient
.convert(FileEncryptionInfoProto.parseFrom(decodedBytes));
}
String location = conn.getHeaderField("Location");
if (location != null) {
// This saves the location for datanode where redirect was issued.
// Need to remove offset because seek can be called after open.
resolvedUrl = removeOffsetParam(new URL(location));
} else {
// This is cached for proxies like httpfsfilesystem.
cachedConnection = conn;
}
originalUrl = super.getUrl();
}
int read(byte[] b, int off, int len) throws IOException {
if (runnerState == RunnerState.CLOSED) {
throw new IOException("Stream closed");
}
if (len == 0) {
return 0;
}
// Before the first read, pos and fileLength will be 0 and readBuffer
// will all be null. They will be initialized once the first connection
// is made. Only after that it makes sense to compare pos and fileLength.
if (pos >= fileLength && readBuffer != null) {
return -1;
}
// If a seek is occurring, the input stream will have been closed, so it
// needs to be reopened. Use the URLRunner to call AbstractRunner#connect
// with the previously-cached resolved URL and with the 'redirected' flag
// set to 'true'. The resolved URL contains the URL of the previously
// opened DN as opposed to the NN. It is preferable to use the resolved
// URL when creating a connection because it does not hit the NN or every
// seek, nor does it open a connection to a new DN after every seek.
// The redirect flag is needed so that AbstractRunner#connect knows the
// URL is already resolved.
// Note that when the redirected flag is set, retries are not attempted.
// So, if the connection fails using URLRunner, clear out the connection
// and fall through to establish the connection using ReadRunner.
if (runnerState == RunnerState.SEEK) {
try {
final URL rurl = new URL(resolvedUrl + "&" + new OffsetParam(pos));
cachedConnection = new URLRunner(GetOpParam.Op.OPEN, rurl, true,
false).run();
} catch (IOException ioe) {
closeInputStream(RunnerState.DISCONNECTED);
}
}
readBuffer = b;
readOffset = off;
readLength = len;
int count = -1;
count = this.run();
if (count >= 0) {
statistics.incrementBytesRead(count);
pos += count;
} else if (pos < fileLength) {
throw new EOFException(
"Premature EOF: pos=" + pos + " < filelength=" + fileLength);
}
return count;
}
void seek(long newPos) throws IOException {
if (pos != newPos) {
pos = newPos;
closeInputStream(RunnerState.SEEK);
}
}
public void close() throws IOException {
closeInputStream(RunnerState.CLOSED);
}
/* The following methods are overriding AbstractRunner methods,
* to be called within the retry policy context by runWithRetry.
*/
@Override
protected URL getUrl() throws IOException {
// This method is called every time either a read is executed.
// The check for connection == null is to ensure that a new URL is only
// created upon a new connection and not for every read.
if (cachedConnection == null) {
// Update URL with current offset. BufferSize doesn't change, but it
// still must be included when creating the new URL.
updateURLParameters(new BufferSizeParam(bufferSize),
new OffsetParam(pos));
originalUrl = super.getUrl();
}
return originalUrl;
}
/* Only make the connection if it is not already open. Don't cache the
* connection here. After this method is called, runWithRetry will call
* validateResponse, and then call the below ReadRunner#getResponse. If
* the code path makes it that far, then we can cache the connection.
*/
@Override
protected HttpURLConnection connect(URL url) throws IOException {
HttpURLConnection conn = cachedConnection;
if (conn == null) {
try {
conn = super.connect(url);
} catch (IOException e) {
closeInputStream(RunnerState.DISCONNECTED);
throw e;
}
}
return conn;
}
/*
* This method is used to perform reads within the retry policy context.
* This code is relying on runWithRetry to always call the above connect
* method and the verifyResponse method prior to calling getResponse.
*/
@Override
Integer getResponse(final HttpURLConnection conn)
throws IOException {
try {
// In the "open-then-read" use case, runWithRetry will have executed
// ReadRunner#connect to make the connection and then executed
// validateResponse to validate the response code. Only then do we want
// to cache the connection.
// In the "read-after-seek" use case, the connection is made and the
// response is validated by the URLRunner. ReadRunner#read then caches
// the connection and the ReadRunner#connect will pass on the cached
// connection
// In either case, stream initialization is done here if necessary.
cachedConnection = conn;
if (in == null) {
in = initializeInputStream(conn);
}
int count = in.read(readBuffer, readOffset, readLength);
if (count < 0 && pos < fileLength) {
throw new EOFException(
"Premature EOF: pos=" + pos + " < filelength=" + fileLength);
}
return Integer.valueOf(count);
} catch (IOException e) {
String redirectHost = resolvedUrl.getAuthority();
if (excludeDatanodes.getValue() != null) {
excludeDatanodes = new ExcludeDatanodesParam(redirectHost + ","
+ excludeDatanodes.getValue());
} else {
excludeDatanodes = new ExcludeDatanodesParam(redirectHost);
}
// If an exception occurs, close the input stream and null it out so
// that if the abstract runner decides to retry, it will reconnect.
closeInputStream(RunnerState.DISCONNECTED);
throw e;
}
}
@VisibleForTesting
InputStream initializeInputStream(HttpURLConnection conn)
throws IOException {
// Cache the resolved URL so that it can be used in the event of
// a future seek operation.
resolvedUrl = removeOffsetParam(conn.getURL());
final String cl = conn.getHeaderField(HttpHeaders.CONTENT_LENGTH);
InputStream inStream = conn.getInputStream();
if (LOG.isDebugEnabled()) {
LOG.debug("open file: " + conn.getURL());
}
if (cl != null) {
long streamLength = Long.parseLong(cl);
fileLength = pos + streamLength;
// Java has a bug with >2GB request streams. It won't bounds check
// the reads so the transfer blocks until the server times out
inStream = new BoundedInputStream(inStream, streamLength);
} else {
fileLength = getHdfsFileStatus(path).getLen();
}
// Wrapping in BufferedInputStream because it is more performant than
// BoundedInputStream by itself.
runnerState = RunnerState.OPEN;
return new BufferedInputStream(inStream, bufferSize);
}
// Close both the InputStream and the connection.
@VisibleForTesting
void closeInputStream(RunnerState rs) throws IOException {
if (in != null) {
IOUtils.close(cachedConnection);
in = null;
}
cachedConnection = null;
runnerState = rs;
}
/* Getters and Setters */
@VisibleForTesting
protected InputStream getInputStream() {
return in;
}
@VisibleForTesting
protected void setInputStream(InputStream inStream) {
in = inStream;
}
Path getPath() {
return path;
}
int getBufferSize() {
return bufferSize;
}
long getFileLength() {
return fileLength;
}
void setFileLength(long len) {
fileLength = len;
}
long getPos() {
return pos;
}
protected FileEncryptionInfo getFileEncryptionInfo() {
return feInfo;
}
}
}
| SPNEGO TLS verification
Signed-off-by: Akira Ajisaka <[email protected]>
| hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java | SPNEGO TLS verification |
|
Java | apache-2.0 | 552c568e75558ae2a9f95e285563c8fc4cb50d66 | 0 | Overseas-Student-Living/jackrabbit,tripodsan/jackrabbit,afilimonov/jackrabbit,kigsmtua/jackrabbit,Overseas-Student-Living/jackrabbit,sdmcraft/jackrabbit,kigsmtua/jackrabbit,Kast0rTr0y/jackrabbit,bartosz-grabski/jackrabbit,SylvesterAbreu/jackrabbit,Kast0rTr0y/jackrabbit,Overseas-Student-Living/jackrabbit,SylvesterAbreu/jackrabbit,SylvesterAbreu/jackrabbit,tripodsan/jackrabbit,sdmcraft/jackrabbit,bartosz-grabski/jackrabbit,bartosz-grabski/jackrabbit,afilimonov/jackrabbit,tripodsan/jackrabbit,sdmcraft/jackrabbit,kigsmtua/jackrabbit,Kast0rTr0y/jackrabbit,afilimonov/jackrabbit | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.xml;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import java.util.ArrayList;
import javax.jcr.AccessDeniedException;
import javax.jcr.ImportUUIDBehavior;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeDefinition;
import org.apache.jackrabbit.core.NodeImpl;
import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.config.ImportConfig;
import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.security.authorization.Permission;
import org.apache.jackrabbit.core.util.ReferenceChangeTracker;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.QPropertyDefinition;
import org.apache.jackrabbit.spi.commons.name.NameConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <code>SessionImporter</code> ...
*/
public class SessionImporter implements Importer {
private static Logger log = LoggerFactory.getLogger(SessionImporter.class);
private final SessionImpl session;
private final NodeImpl importTargetNode;
private final int uuidBehavior;
private Stack<NodeImpl> parents;
/**
* helper object that keeps track of remapped uuid's and imported reference
* properties that might need correcting depending on the uuid mappings
*/
private final ReferenceChangeTracker refTracker;
private final List<ProtectedNodeImporter> pnImporters = new ArrayList();
/**
* Available importers for protected properties.
*/
private final List<ProtectedPropertyImporter> ppImporters = new ArrayList();
/**
* Currently active importer for protected nodes.
*/
private ProtectedNodeImporter pnImporter = null;
/**
* Creates a new <code>SessionImporter</code> instance.
*
* @param importTargetNode the target node
* @param session session
* @param uuidBehavior any of the constants declared by
* {@link javax.jcr.ImportUUIDBehavior}
*/
public SessionImporter(NodeImpl importTargetNode,
SessionImpl session,
int uuidBehavior) {
this(importTargetNode, session, uuidBehavior, null);
}
/**
* Creates a new <code>SessionImporter</code> instance.
*
* @param importTargetNode the target node
* @param session session
* @param uuidBehavior the desired uuid behavior as defined
* by {@link javax.jcr.ImportUUIDBehavior}.
* @param config
*/
public SessionImporter(NodeImpl importTargetNode, SessionImpl session,
int uuidBehavior, ImportConfig config) {
this.importTargetNode = importTargetNode;
this.session = session;
this.uuidBehavior = uuidBehavior;
refTracker = new ReferenceChangeTracker();
parents = new Stack<NodeImpl>();
parents.push(importTargetNode);
if (config != null) {
List<ProtectedNodeImporter> ln = config.getProtectedNodeImporters();
for (ProtectedNodeImporter pni : ln) {
if (pni.init(session, session, false, uuidBehavior, refTracker)) {
pnImporters.add(pni);
}
}
List<ProtectedPropertyImporter> lp = config.getProtectedPropertyImporters();
for (ProtectedPropertyImporter ppi : lp) {
if (ppi.init(session, session, false, uuidBehavior, refTracker)) {
ppImporters.add(ppi);
}
}
}
// missing config -> initialize defaults.
if (pnImporters.isEmpty()) {
ProtectedNodeImporter def = new DefaultProtectedNodeImporter();
if (def.init(session, session, false, uuidBehavior, refTracker)) {
pnImporters.add(def);
}
}
if (ppImporters.isEmpty()) {
DefaultProtectedPropertyImporter def = new DefaultProtectedPropertyImporter();
if (def.init(session, session, false, uuidBehavior, refTracker)) {
ppImporters.add(def);
}
}
}
/**
* make sure the editing session is allowed create nodes with a
* specified node type (and ev. mixins),<br>
* NOTE: this check is not executed in a single place as the parent
* may change in case of
* {@link javax.jcr.ImportUUIDBehavior#IMPORT_UUID_COLLISION_REPLACE_EXISTING IMPORT_UUID_COLLISION_REPLACE_EXISTING}.
*
* @param parent parent node
* @param nodeName the name
* @throws RepositoryException if an error occurs
*/
protected void checkPermission(NodeImpl parent, Name nodeName)
throws RepositoryException {
if (!session.getAccessManager().isGranted(session.getQPath(parent.getPath()), nodeName, Permission.NODE_TYPE_MNGMT)) {
throw new AccessDeniedException("Insufficient permission.");
}
}
protected NodeImpl createNode(NodeImpl parent,
Name nodeName,
Name nodeTypeName,
Name[] mixinNames,
NodeId id)
throws RepositoryException {
NodeImpl node;
// add node
node = parent.addNode(nodeName, nodeTypeName, id);
// add mixins
if (mixinNames != null) {
for (Name mixinName : mixinNames) {
node.addMixin(mixinName);
}
}
return node;
}
protected void createProperty(NodeImpl node, PropInfo pInfo, QPropertyDefinition def) throws RepositoryException {
// convert serialized values to Value objects
Value[] va = pInfo.getValues(pInfo.getTargetType(def), session);
// multi- or single-valued property?
Name name = pInfo.getName();
int type = pInfo.getType();
if (va.length == 1 && !def.isMultiple()) {
Exception e = null;
try {
// set single-value
node.setProperty(name, va[0]);
} catch (ValueFormatException vfe) {
e = vfe;
} catch (ConstraintViolationException cve) {
e = cve;
}
if (e != null) {
// setting single-value failed, try setting value array
// as a last resort (in case there are ambiguous property
// definitions)
node.setProperty(name, va, type);
}
} else {
// can only be multi-valued (n == 0 || n > 1)
node.setProperty(name, va, type);
}
if (type == PropertyType.REFERENCE || type == PropertyType.WEAKREFERENCE) {
// store reference for later resolution
refTracker.processedReference(node.getProperty(name));
}
}
protected NodeImpl resolveUUIDConflict(NodeImpl parent,
NodeImpl conflicting,
NodeInfo nodeInfo)
throws RepositoryException {
NodeImpl node;
if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW) {
// create new with new uuid
checkPermission(parent, nodeInfo.getName());
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(), null);
// remember uuid mapping
if (node.isNodeType(NameConstants.MIX_REFERENCEABLE)) {
refTracker.mappedId(nodeInfo.getId(), node.getNodeId());
}
} else if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW) {
// if conflicting node is shareable, then clone it
if (conflicting.isNodeType(NameConstants.MIX_SHAREABLE)) {
parent.clone(conflicting, nodeInfo.getName());
return null;
}
String msg = "a node with uuid " + nodeInfo.getId() + " already exists!";
log.debug(msg);
throw new ItemExistsException(msg);
} else if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING) {
// make sure conflicting node is not importTargetNode or an ancestor thereof
if (importTargetNode.getPath().startsWith(conflicting.getPath())) {
String msg = "cannot remove ancestor node";
log.debug(msg);
throw new ConstraintViolationException (msg);
}
// remove conflicting
conflicting.remove();
// create new with given uuid
checkPermission(parent, nodeInfo.getName());
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(),
nodeInfo.getId());
} else if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING) {
if (conflicting.getDepth() == 0) {
String msg = "root node cannot be replaced";
log.debug(msg);
throw new RepositoryException(msg);
}
// 'replace' current parent with parent of conflicting
parent = (NodeImpl) conflicting.getParent();
// replace child node
checkPermission(parent, nodeInfo.getName());
node = parent.replaceChildNode(nodeInfo.getId(), nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames());
} else {
String msg = "unknown uuidBehavior: " + uuidBehavior;
log.debug(msg);
throw new RepositoryException(msg);
}
return node;
}
//-------------------------------------------------------------< Importer >
/**
* {@inheritDoc}
*/
public void start() throws RepositoryException {
// nop
}
/**
* {@inheritDoc}
*/
public void startNode(NodeInfo nodeInfo, List<PropInfo> propInfos)
throws RepositoryException {
NodeImpl parent = parents.peek();
// process node
NodeImpl node = null;
NodeId id = nodeInfo.getId();
Name nodeName = nodeInfo.getName();
Name ntName = nodeInfo.getNodeTypeName();
Name[] mixins = nodeInfo.getMixinNames();
if (parent == null) {
log.debug("Skipping node: " + nodeName);
// parent node was skipped, skip this child node too
parents.push(null); // push null onto stack for skipped node
// notify the p-i-importer
if (pnImporter != null) {
pnImporter.startChildInfo(nodeInfo, propInfos);
}
return;
}
if (parent.getDefinition().isProtected()) {
// skip protected node
parents.push(null);
log.debug("Skipping protected node: " + nodeName);
// Notify the ProtectedNodeImporter about the start of a item
// tree that is protected by this parent. If it potentially is
// able to deal with it, notify it about the child node.
for (ProtectedNodeImporter pni : pnImporters) {
if (pni.start(parent)) {
log.debug("Protected node -> delegated to ProtectedPropertyImporter");
pnImporter = pni;
pnImporter.startChildInfo(nodeInfo, propInfos);
break;
} /* else: p-i-Importer isn't able to deal with the protected tree.
try next. and if none can handle the passed parent the
tree below will be skipped */
}
return;
}
if (parent.hasNode(nodeName)) {
// a node with that name already exists...
NodeImpl existing = parent.getNode(nodeName);
NodeDefinition def = existing.getDefinition();
if (!def.allowsSameNameSiblings()) {
// existing doesn't allow same-name siblings,
// check for potential conflicts
if (def.isProtected() && existing.isNodeType(ntName)) {
/*
use the existing node as parent for the possible subsequent
import of a protected tree, that the protected node importer
may or may not be able to deal with.
-> upon the next 'startNode' the check for the parent being
protected will notify the protected node importer.
-> if the importer is able to deal with that node it needs
to care of the complete subtree until it is notified
during the 'endNode' call.
-> if the import can't deal with that node or if that node
is the a leaf in the tree to be imported 'end' will
not have an effect on the importer, that was never started.
*/
log.debug("Skipping protected node: " + existing);
parents.push(existing);
return;
}
if (def.isAutoCreated() && existing.isNodeType(ntName)) {
// this node has already been auto-created, no need to create it
node = existing;
} else {
// edge case: colliding node does have same uuid
// (see http://issues.apache.org/jira/browse/JCR-1128)
if (!(existing.getId().equals(id)
&& (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING
|| uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING))) {
throw new ItemExistsException(
"Node with the same UUID exists:" + existing);
}
// fall through
}
}
}
if (node == null) {
// create node
if (id == null) {
// no potential uuid conflict, always add new node
checkPermission(parent, nodeName);
node = createNode(parent, nodeName, ntName, mixins, null);
} else {
// potential uuid conflict
NodeImpl conflicting;
try {
conflicting = session.getNodeById(id);
} catch (ItemNotFoundException infe) {
conflicting = null;
}
if (conflicting != null) {
// resolve uuid conflict
node = resolveUUIDConflict(parent, conflicting, nodeInfo);
if (node == null) {
// no new node has been created, so skip this node
parents.push(null); // push null onto stack for skipped node
log.debug("Skipping existing node " + nodeInfo.getName());
return;
}
} else {
// create new with given uuid
checkPermission(parent, nodeName);
node = createNode(parent, nodeName, ntName, mixins, id);
}
}
}
// process properties
for (PropInfo pi : propInfos) {
// find applicable definition
QPropertyDefinition def = pi.getApplicablePropertyDef(node.getEffectiveNodeType());
if (def.isProtected()) {
// skip protected property
log.debug("Skipping protected property " + pi.getName());
// notify the ProtectedPropertyImporter.
for (ProtectedPropertyImporter ppi : ppImporters) {
if (ppi.handlePropInfo(node, pi, def)) {
log.debug("Protected property -> delegated to ProtectedPropertyImporter");
break;
} /* else: p-i-Importer isn't able to deal with this property.
try next pp-importer */
}
} else {
// regular property -> create the property
createProperty(node, pi, def);
}
}
parents.push(node);
}
/**
* {@inheritDoc}
*/
public void endNode(NodeInfo nodeInfo) throws RepositoryException {
NodeImpl parent = parents.pop();
if (parent == null) {
if (pnImporter != null) {
pnImporter.endChildInfo();
}
} else if (parent.getDefinition().isProtected()) {
if (pnImporter != null) {
pnImporter.end(parent);
// and reset the pnImporter field waiting for the next protected
// parent -> selecting again from available importers
pnImporter = null;
}
}
}
/**
* {@inheritDoc}
*/
public void end() throws RepositoryException {
/**
* adjust references that refer to uuid's which have been mapped to
* newly generated uuid's on import
*/
// 1. let protected property/node importers handle protected ref-properties
// and (protected) properties underneith a protected parent node.
for (ProtectedPropertyImporter ppi : ppImporters) {
ppi.processReferences();
}
for (ProtectedNodeImporter pni : pnImporters) {
pni.processReferences();
}
// 2. regular non-protected properties.
Iterator<Object> iter = refTracker.getProcessedReferences();
while (iter.hasNext()) {
Object ref = iter.next();
if (!(ref instanceof Property)) {
continue;
}
Property prop = (Property) ref;
// being paranoid...
if (prop.getType() != PropertyType.REFERENCE
&& prop.getType() != PropertyType.WEAKREFERENCE) {
continue;
}
if (prop.isMultiple()) {
Value[] values = prop.getValues();
Value[] newVals = new Value[values.length];
for (int i = 0; i < values.length; i++) {
Value val = values[i];
NodeId original = new NodeId(val.getString());
NodeId adjusted = refTracker.getMappedId(original);
if (adjusted != null) {
newVals[i] = session.getValueFactory().createValue(
session.getNodeById(adjusted),
prop.getType() != PropertyType.REFERENCE);
} else {
// reference doesn't need adjusting, just copy old value
newVals[i] = val;
}
}
prop.setValue(newVals);
} else {
Value val = prop.getValue();
NodeId original = new NodeId(val.getString());
NodeId adjusted = refTracker.getMappedId(original);
if (adjusted != null) {
prop.setValue(session.getNodeById(adjusted).getUUID());
}
}
}
refTracker.clear();
}
}
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/xml/SessionImporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.xml;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import java.util.ArrayList;
import javax.jcr.AccessDeniedException;
import javax.jcr.ImportUUIDBehavior;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeDefinition;
import org.apache.jackrabbit.core.NodeImpl;
import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.config.ImportConfig;
import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.security.authorization.Permission;
import org.apache.jackrabbit.core.util.ReferenceChangeTracker;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.QPropertyDefinition;
import org.apache.jackrabbit.spi.commons.name.NameConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <code>SessionImporter</code> ...
*/
public class SessionImporter implements Importer {
private static Logger log = LoggerFactory.getLogger(SessionImporter.class);
private final SessionImpl session;
private final NodeImpl importTargetNode;
private final int uuidBehavior;
private Stack<NodeImpl> parents;
/**
* helper object that keeps track of remapped uuid's and imported reference
* properties that might need correcting depending on the uuid mappings
*/
private final ReferenceChangeTracker refTracker;
private final List<ProtectedNodeImporter> pnImporters = new ArrayList();
/**
* Available importers for protected properties.
*/
private final List<ProtectedPropertyImporter> ppImporters = new ArrayList();
/**
* Currently active importer for protected nodes.
*/
private ProtectedNodeImporter pnImporter = null;
/**
* Creates a new <code>SessionImporter</code> instance.
*
* @param importTargetNode the target node
* @param session session
* @param uuidBehavior any of the constants declared by
* {@link javax.jcr.ImportUUIDBehavior}
*/
public SessionImporter(NodeImpl importTargetNode,
SessionImpl session,
int uuidBehavior) {
this(importTargetNode, session, uuidBehavior, null);
}
/**
* Creates a new <code>SessionImporter</code> instance.
*
* @param importTargetNode the target node
* @param session session
* @param uuidBehavior the uuid behaviro
* @param config
*/
public SessionImporter(NodeImpl importTargetNode, SessionImpl session,
int uuidBehavior, ImportConfig config) {
this.importTargetNode = importTargetNode;
this.session = session;
this.uuidBehavior = uuidBehavior;
refTracker = new ReferenceChangeTracker();
parents = new Stack<NodeImpl>();
parents.push(importTargetNode);
if (config != null) {
List<ProtectedNodeImporter> ln = config.getProtectedNodeImporters();
for (ProtectedNodeImporter pni : ln) {
if (pni.init(session, session, false, uuidBehavior, refTracker)) {
pnImporters.add(pni);
}
}
List<ProtectedPropertyImporter> lp = config.getProtectedPropertyImporters();
for (ProtectedPropertyImporter ppi : lp) {
if (ppi.init(session, session, false, uuidBehavior, refTracker)) {
ppImporters.add(ppi);
}
}
}
// missing config -> initialize defaults.
if (pnImporters.isEmpty()) {
ProtectedNodeImporter def = new DefaultProtectedNodeImporter();
if (def.init(session, session, false, uuidBehavior, refTracker)) {
pnImporters.add(def);
}
}
if (ppImporters.isEmpty()) {
DefaultProtectedPropertyImporter def = new DefaultProtectedPropertyImporter();
if (def.init(session, session, false, uuidBehavior, refTracker)) {
ppImporters.add(def);
}
}
}
/**
* make sure the editing session is allowed create nodes with a
* specified node type (and ev. mixins),<br>
* NOTE: this check is not executed in a single place as the parent
* may change in case of
* {@link javax.jcr.ImportUUIDBehavior#IMPORT_UUID_COLLISION_REPLACE_EXISTING IMPORT_UUID_COLLISION_REPLACE_EXISTING}.
*
* @param parent parent node
* @param nodeName the name
* @throws RepositoryException if an error occurs
*/
protected void checkPermission(NodeImpl parent, Name nodeName)
throws RepositoryException {
if (!session.getAccessManager().isGranted(session.getQPath(parent.getPath()), nodeName, Permission.NODE_TYPE_MNGMT)) {
throw new AccessDeniedException("Insufficient permission.");
}
}
protected NodeImpl createNode(NodeImpl parent,
Name nodeName,
Name nodeTypeName,
Name[] mixinNames,
NodeId id)
throws RepositoryException {
NodeImpl node;
// add node
node = parent.addNode(nodeName, nodeTypeName, id);
// add mixins
if (mixinNames != null) {
for (Name mixinName : mixinNames) {
node.addMixin(mixinName);
}
}
return node;
}
protected void createProperty(NodeImpl node, PropInfo pInfo, QPropertyDefinition def) throws RepositoryException {
// convert serialized values to Value objects
Value[] va = pInfo.getValues(pInfo.getTargetType(def), session);
// multi- or single-valued property?
Name name = pInfo.getName();
int type = pInfo.getType();
if (va.length == 1 && !def.isMultiple()) {
Exception e = null;
try {
// set single-value
node.setProperty(name, va[0]);
} catch (ValueFormatException vfe) {
e = vfe;
} catch (ConstraintViolationException cve) {
e = cve;
}
if (e != null) {
// setting single-value failed, try setting value array
// as a last resort (in case there are ambiguous property
// definitions)
node.setProperty(name, va, type);
}
} else {
// can only be multi-valued (n == 0 || n > 1)
node.setProperty(name, va, type);
}
if (type == PropertyType.REFERENCE || type == PropertyType.WEAKREFERENCE) {
// store reference for later resolution
refTracker.processedReference(node.getProperty(name));
}
}
protected NodeImpl resolveUUIDConflict(NodeImpl parent,
NodeImpl conflicting,
NodeInfo nodeInfo)
throws RepositoryException {
NodeImpl node;
if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW) {
// create new with new uuid
checkPermission(parent, nodeInfo.getName());
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(), null);
// remember uuid mapping
if (node.isNodeType(NameConstants.MIX_REFERENCEABLE)) {
refTracker.mappedId(nodeInfo.getId(), node.getNodeId());
}
} else if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW) {
// if conflicting node is shareable, then clone it
if (conflicting.isNodeType(NameConstants.MIX_SHAREABLE)) {
parent.clone(conflicting, nodeInfo.getName());
return null;
}
String msg = "a node with uuid " + nodeInfo.getId() + " already exists!";
log.debug(msg);
throw new ItemExistsException(msg);
} else if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING) {
// make sure conflicting node is not importTargetNode or an ancestor thereof
if (importTargetNode.getPath().startsWith(conflicting.getPath())) {
String msg = "cannot remove ancestor node";
log.debug(msg);
throw new ConstraintViolationException (msg);
}
// remove conflicting
conflicting.remove();
// create new with given uuid
checkPermission(parent, nodeInfo.getName());
node = createNode(parent, nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames(),
nodeInfo.getId());
} else if (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING) {
if (conflicting.getDepth() == 0) {
String msg = "root node cannot be replaced";
log.debug(msg);
throw new RepositoryException(msg);
}
// 'replace' current parent with parent of conflicting
parent = (NodeImpl) conflicting.getParent();
// replace child node
checkPermission(parent, nodeInfo.getName());
node = parent.replaceChildNode(nodeInfo.getId(), nodeInfo.getName(),
nodeInfo.getNodeTypeName(), nodeInfo.getMixinNames());
} else {
String msg = "unknown uuidBehavior: " + uuidBehavior;
log.debug(msg);
throw new RepositoryException(msg);
}
return node;
}
//-------------------------------------------------------------< Importer >
/**
* {@inheritDoc}
*/
public void start() throws RepositoryException {
// nop
}
/**
* {@inheritDoc}
*/
public void startNode(NodeInfo nodeInfo, List<PropInfo> propInfos)
throws RepositoryException {
NodeImpl parent = parents.peek();
// process node
NodeImpl node = null;
NodeId id = nodeInfo.getId();
Name nodeName = nodeInfo.getName();
Name ntName = nodeInfo.getNodeTypeName();
Name[] mixins = nodeInfo.getMixinNames();
if (parent == null) {
log.debug("Skipping node: " + nodeName);
// parent node was skipped, skip this child node too
parents.push(null); // push null onto stack for skipped node
// notify the p-i-importer
if (pnImporter != null) {
pnImporter.startChildInfo(nodeInfo, propInfos);
}
return;
}
if (parent.getDefinition().isProtected()) {
// skip protected node
parents.push(null);
log.debug("Skipping protected node: " + nodeName);
// Notify the ProtectedNodeImporter about the start of a item
// tree that is protected by this parent. If it potentially is
// able to deal with it, notify it about the child node.
for (ProtectedNodeImporter pni : pnImporters) {
if (pni.start(parent)) {
log.debug("Protected node -> delegated to ProtectedPropertyImporter");
pnImporter = pni;
pnImporter.startChildInfo(nodeInfo, propInfos);
break;
} /* else: p-i-Importer isn't able to deal with the protected tree.
try next. and if none can handle the passed parent the
tree below will be skipped */
}
return;
}
if (parent.hasNode(nodeName)) {
// a node with that name already exists...
NodeImpl existing = parent.getNode(nodeName);
NodeDefinition def = existing.getDefinition();
if (!def.allowsSameNameSiblings()) {
// existing doesn't allow same-name siblings,
// check for potential conflicts
if (def.isProtected() && existing.isNodeType(ntName)) {
/*
use the existing node as parent for the possible subsequent
import of a protected tree, that the protected node importer
may or may not be able to deal with.
-> upon the next 'startNode' the check for the parent being
protected will notify the protected node importer.
-> if the importer is able to deal with that node it needs
to care of the complete subtree until it is notified
during the 'endNode' call.
-> if the import can't deal with that node or if that node
is the a leaf in the tree to be imported 'end' will
not have an effect on the importer, that was never started.
*/
log.debug("Skipping protected node: " + existing);
parents.push(existing);
return;
}
if (def.isAutoCreated() && existing.isNodeType(ntName)) {
// this node has already been auto-created, no need to create it
node = existing;
} else {
// edge case: colliding node does have same uuid
// (see http://issues.apache.org/jira/browse/JCR-1128)
if (!(existing.getId().equals(id)
&& (uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING
|| uuidBehavior == ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING))) {
throw new ItemExistsException(
"Node with the same UUID exists:" + existing);
}
// fall through
}
}
}
if (node == null) {
// create node
if (id == null) {
// no potential uuid conflict, always add new node
checkPermission(parent, nodeName);
node = createNode(parent, nodeName, ntName, mixins, null);
} else {
// potential uuid conflict
NodeImpl conflicting;
try {
conflicting = session.getNodeById(id);
} catch (ItemNotFoundException infe) {
conflicting = null;
}
if (conflicting != null) {
// resolve uuid conflict
node = resolveUUIDConflict(parent, conflicting, nodeInfo);
if (node == null) {
// no new node has been created, so skip this node
parents.push(null); // push null onto stack for skipped node
log.debug("Skipping existing node " + nodeInfo.getName());
return;
}
} else {
// create new with given uuid
checkPermission(parent, nodeName);
node = createNode(parent, nodeName, ntName, mixins, id);
}
}
}
// process properties
for (PropInfo pi : propInfos) {
// find applicable definition
QPropertyDefinition def = pi.getApplicablePropertyDef(node.getEffectiveNodeType());
if (def.isProtected()) {
// skip protected property
log.debug("Skipping protected property " + pi.getName());
// notify the ProtectedPropertyImporter.
for (ProtectedPropertyImporter ppi : ppImporters) {
if (ppi.handlePropInfo(node, pi, def)) {
log.debug("Protected property -> delegated to ProtectedPropertyImporter");
break;
} /* else: p-i-Importer isn't able to deal with this property.
try next pp-importer */
}
} else {
// regular property -> create the property
createProperty(node, pi, def);
}
}
parents.push(node);
}
/**
* {@inheritDoc}
*/
public void endNode(NodeInfo nodeInfo) throws RepositoryException {
NodeImpl parent = parents.pop();
if (parent == null) {
if (pnImporter != null) {
pnImporter.endChildInfo();
}
} else if (parent.getDefinition().isProtected()) {
if (pnImporter != null) {
pnImporter.end(parent);
// and reset the pnImporter field waiting for the next protected
// parent -> selecting again from available importers
pnImporter = null;
}
}
}
/**
* {@inheritDoc}
*/
public void end() throws RepositoryException {
/**
* adjust references that refer to uuid's which have been mapped to
* newly generated uuid's on import
*/
// 1. let protected property/node importers handle protected ref-properties
// and (protected) properties underneith a protected parent node.
for (ProtectedPropertyImporter ppi : ppImporters) {
ppi.processReferences();
}
for (ProtectedNodeImporter pni : pnImporters) {
pni.processReferences();
}
// 2. regular non-protected properties.
Iterator<Object> iter = refTracker.getProcessedReferences();
while (iter.hasNext()) {
Object ref = iter.next();
if (!(ref instanceof Property)) {
continue;
}
Property prop = (Property) ref;
// being paranoid...
if (prop.getType() != PropertyType.REFERENCE
&& prop.getType() != PropertyType.WEAKREFERENCE) {
continue;
}
if (prop.isMultiple()) {
Value[] values = prop.getValues();
Value[] newVals = new Value[values.length];
for (int i = 0; i < values.length; i++) {
Value val = values[i];
NodeId original = new NodeId(val.getString());
NodeId adjusted = refTracker.getMappedId(original);
if (adjusted != null) {
newVals[i] = session.getValueFactory().createValue(
session.getNodeById(adjusted),
prop.getType() != PropertyType.REFERENCE);
} else {
// reference doesn't need adjusting, just copy old value
newVals[i] = val;
}
}
prop.setValue(newVals);
} else {
Value val = prop.getValue();
NodeId original = new NodeId(val.getString());
NodeId adjusted = refTracker.getMappedId(original);
if (adjusted != null) {
prop.setValue(session.getNodeById(adjusted).getUUID());
}
}
}
refTracker.clear();
}
}
| typo
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@884167 13f79535-47bb-0310-9956-ffa450edef68
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/xml/SessionImporter.java | typo |
|
Java | apache-2.0 | 878d332a0bd7374190a85a23d3a6241d930289f3 | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.MetricRegistry;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.client.solrj.impl.HttpClientUtil;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.GenericSolrRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.RequestWriter.StringPayloadContentWriter;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.request.V2Request;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.cloud.SolrCloudAuthTestCase;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.Utils;
import org.apache.solr.common.util.TimeSource;
import org.apache.solr.util.SolrCLI;
import org.apache.solr.util.TimeOut;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonMap;
public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final String COLLECTION = "authCollection";
@Before
public void setupCluster() throws Exception {
configureCluster(3)
.addConfig("conf", configset("cloud-minimal"))
.configure();
CollectionAdminRequest.createCollection(COLLECTION, "conf", 3, 1).process(cluster.getSolrClient());
cluster.waitForActiveCollection(COLLECTION, 3, 3);
}
@After
public void tearDownCluster() throws Exception {
shutdownCluster();
}
@Test
//commented 9-Aug-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 21-May-2018
// commented out on: 17-Feb-2019 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // annotated on: 24-Dec-2018
public void testBasicAuth() throws Exception {
boolean isUseV2Api = random().nextBoolean();
String authcPrefix = "/admin/authentication";
String authzPrefix = "/admin/authorization";
if(isUseV2Api){
authcPrefix = "/____v2/cluster/security/authentication";
authzPrefix = "/____v2/cluster/security/authorization";
}
NamedList<Object> rsp;
HttpClient cl = null;
try {
cl = HttpClientUtil.createClient(null);
JettySolrRunner randomJetty = cluster.getRandomJetty(random());
String baseUrl = randomJetty.getBaseUrl().toString();
verifySecurityStatus(cl, baseUrl + authcPrefix, "/errorMessages", null, 20);
zkClient().setData("/security.json", STD_CONF.replaceAll("'", "\"").getBytes(UTF_8), true);
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/class", "solr.BasicAuthPlugin", 20);
randomJetty.stop();
cluster.waitForJettyToStop(randomJetty);
randomJetty.start();
cluster.waitForAllNodes(30);
cluster.waitForActiveCollection(COLLECTION, 3, 3);
baseUrl = randomJetty.getBaseUrl().toString();
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/class", "solr.BasicAuthPlugin", 20);
assertNumberOfMetrics(16); // Basic auth metrics available
assertAuthMetricsMinimums(1, 0, 1, 0, 0, 0);
assertPkiAuthMetricsMinimums(0, 0, 0, 0, 0, 0);
String command = "{\n" +
"'set-user': {'harry':'HarryIsCool'}\n" +
"}";
final SolrRequest genericReq;
if (isUseV2Api) {
genericReq = new V2Request.Builder("/cluster/security/authentication")
.withPayload(command)
.withMethod(SolrRequest.METHOD.POST).build();
} else {
genericReq = new GenericSolrRequest(SolrRequest.METHOD.POST, authcPrefix, new ModifiableSolrParams());
((GenericSolrRequest)genericReq).setContentWriter(new StringPayloadContentWriter(command, CommonParams.JSON_MIME));
}
// avoid bad connection races due to shutdown
cluster.getSolrClient().getHttpClient().getConnectionManager().closeExpiredConnections();
cluster.getSolrClient().getHttpClient().getConnectionManager().closeIdleConnections(1, TimeUnit.MILLISECONDS);
HttpSolrClient.RemoteSolrException exp = expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
cluster.getSolrClient().request(genericReq);
});
assertEquals(401, exp.code());
assertAuthMetricsMinimums(2, 0, 2, 0, 0, 0);
assertPkiAuthMetricsMinimums(0, 0, 0, 0, 0, 0);
command = "{\n" +
"'set-user': {'harry':'HarryIsUberCool'}\n" +
"}";
HttpPost httpPost = new HttpPost(baseUrl + authcPrefix);
setAuthorizationHeader(httpPost, makeBasicAuthHeader("solr", "SolrRocks"));
httpPost.setEntity(new ByteArrayEntity(command.getBytes(UTF_8)));
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication.enabled", "true", 20);
HttpResponse r = cl.execute(httpPost);
int statusCode = r.getStatusLine().getStatusCode();
Utils.consumeFully(r.getEntity());
assertEquals("proper_cred sent, but access denied", 200, statusCode);
assertPkiAuthMetricsMinimums(0, 0, 0, 0, 0, 0);
assertAuthMetricsMinimums(4, 1, 3, 0, 0, 0);
baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/credentials/harry", NOT_NULL_PREDICATE, 20);
command = "{\n" +
"'set-user-role': {'harry':'admin'}\n" +
"}";
executeCommand(baseUrl + authzPrefix, cl,command, "solr", "SolrRocks");
assertAuthMetricsMinimums(5, 2, 3, 0, 0, 0);
baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
verifySecurityStatus(cl, baseUrl + authzPrefix, "authorization/user-role/harry", NOT_NULL_PREDICATE, 20);
executeCommand(baseUrl + authzPrefix, cl, Utils.toJSONString(singletonMap("set-permission", Utils.makeMap
("collection", "x",
"path", "/update/*",
"role", "dev"))), "harry", "HarryIsUberCool" );
verifySecurityStatus(cl, baseUrl + authzPrefix, "authorization/permissions[1]/collection", "x", 20);
assertAuthMetricsMinimums(8, 3, 5, 0, 0, 0);
executeCommand(baseUrl + authzPrefix, cl,Utils.toJSONString(singletonMap("set-permission", Utils.makeMap
("name", "collection-admin-edit", "role", "admin"))), "harry", "HarryIsUberCool" );
verifySecurityStatus(cl, baseUrl + authzPrefix, "authorization/permissions[2]/name", "collection-admin-edit", 20);
assertAuthMetricsMinimums(10, 4, 6, 0, 0, 0);
CollectionAdminRequest.Reload reload = CollectionAdminRequest.reloadCollection(COLLECTION);
try (HttpSolrClient solrClient = getHttpSolrClient(baseUrl)) {
expectThrows(HttpSolrClient.RemoteSolrException.class, () -> solrClient.request(reload));
reload.setMethod(SolrRequest.METHOD.POST);
expectThrows(HttpSolrClient.RemoteSolrException.class, () -> solrClient.request(reload));
}
cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION)
.setBasicAuthCredentials("harry", "HarryIsUberCool"));
expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION)
.setBasicAuthCredentials("harry", "Cool12345"));
});
assertAuthMetricsMinimums(14, 5, 8, 1, 0, 0);
executeCommand(baseUrl + authzPrefix, cl,"{set-permission : { name : update , role : admin}}", "harry", "HarryIsUberCool");
UpdateRequest del = new UpdateRequest().deleteByQuery("*:*");
del.setBasicAuthCredentials("harry","HarryIsUberCool");
del.setCommitWithin(10);
del.process(cluster.getSolrClient(), COLLECTION);
//Test for SOLR-12514. Create a new jetty . This jetty does not have the collection.
//Make a request to that jetty and it should fail
JettySolrRunner aNewJetty = cluster.startJettySolrRunner();
SolrClient aNewClient = aNewJetty.newClient();
UpdateRequest delQuery = null;
delQuery = new UpdateRequest().deleteByQuery("*:*");
delQuery.setBasicAuthCredentials("harry","HarryIsUberCool");
delQuery.process(aNewClient, COLLECTION);//this should succeed
try {
HttpSolrClient.RemoteSolrException e = expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
new UpdateRequest().deleteByQuery("*:*").process(aNewClient, COLLECTION);
});
assertTrue(e.getMessage().contains("Unauthorized request"));
} finally {
aNewClient.close();
cluster.stopJettySolrRunner(aNewJetty);
}
addDocument("harry","HarryIsUberCool","id", "4");
executeCommand(baseUrl + authcPrefix, cl, "{set-property : { blockUnknown: true}}", "harry", "HarryIsUberCool");
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/blockUnknown", "true", 20, "harry", "HarryIsUberCool");
verifySecurityStatus(cl, baseUrl + "/admin/info/key", "key", NOT_NULL_PREDICATE, 20);
assertAuthMetricsMinimums(17, 8, 8, 1, 0, 0);
String[] toolArgs = new String[]{
"status", "-solr", baseUrl};
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream stdoutSim = new PrintStream(baos, true, StandardCharsets.UTF_8.name());
SolrCLI.StatusTool tool = new SolrCLI.StatusTool(stdoutSim);
try {
System.setProperty("basicauth", "harry:HarryIsUberCool");
tool.runTool(SolrCLI.processCommandLineArgs(SolrCLI.joinCommonAndToolOptions(tool.getOptions()), toolArgs));
Map obj = (Map) Utils.fromJSON(new ByteArrayInputStream(baos.toByteArray()));
assertTrue(obj.containsKey("version"));
assertTrue(obj.containsKey("startTime"));
assertTrue(obj.containsKey("uptime"));
assertTrue(obj.containsKey("memory"));
} catch (Exception e) {
log.error("RunExampleTool failed due to: " + e +
"; stdout from tool prior to failure: " + baos.toString(StandardCharsets.UTF_8.name()));
}
SolrParams params = new MapSolrParams(Collections.singletonMap("q", "*:*"));
// Query that fails due to missing credentials
exp = expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
cluster.getSolrClient().query(COLLECTION, params);
});
assertEquals(401, exp.code());
assertAuthMetricsMinimums(19, 8, 8, 1, 2, 0);
assertPkiAuthMetricsMinimums(3, 3, 0, 0, 0, 0);
// Query that succeeds
GenericSolrRequest req = new GenericSolrRequest(SolrRequest.METHOD.GET, "/select", params);
req.setBasicAuthCredentials("harry", "HarryIsUberCool");
cluster.getSolrClient().request(req, COLLECTION);
assertAuthMetricsMinimums(20, 8, 8, 1, 2, 0);
assertPkiAuthMetricsMinimums(10, 10, 0, 0, 0, 0);
addDocument("harry","HarryIsUberCool","id", "5");
assertAuthMetricsMinimums(23, 11, 9, 1, 2, 0);
assertPkiAuthMetricsMinimums(14, 14, 0, 0, 0, 0);
// Reindex collection depends on streaming request that needs to authenticate against new collection
CollectionAdminRequest.ReindexCollection reindexReq = CollectionAdminRequest.reindexCollection(COLLECTION);
reindexReq.setBasicAuthCredentials("harry", "HarryIsUberCool");
cluster.getSolrClient().request(reindexReq, COLLECTION);
assertAuthMetricsMinimums(24, 12, 9, 1, 2, 0);
assertPkiAuthMetricsMinimums(15, 15, 0, 0, 0, 0);
// Validate forwardCredentials
assertEquals(1, executeQuery(params("q", "id:5"), "harry", "HarryIsUberCool").getResults().getNumFound());
assertAuthMetricsMinimums(25, 13, 9, 1, 2, 0);
assertPkiAuthMetricsMinimums(19, 19, 0, 0, 0, 0);
executeCommand(baseUrl + authcPrefix, cl, "{set-property : { forwardCredentials: true}}", "harry", "HarryIsUberCool");
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/forwardCredentials", "true", 20, "harry", "HarryIsUberCool");
assertEquals(1, executeQuery(params("q", "id:5"), "harry", "HarryIsUberCool").getResults().getNumFound());
assertAuthMetricsMinimums(32, 20, 9, 1, 2, 0);
assertPkiAuthMetricsMinimums(19, 19, 0, 0, 0, 0);
executeCommand(baseUrl + authcPrefix, cl, "{set-property : { blockUnknown: false}}", "harry", "HarryIsUberCool");
} finally {
if (cl != null) {
HttpClientUtil.close(cl);
}
}
}
private void assertNumberOfMetrics(int num) {
MetricRegistry registry0 = cluster.getJettySolrRunner(0).getCoreContainer().getMetricManager().registry("solr.node");
assertNotNull(registry0);
assertEquals(num, registry0.getMetrics().entrySet().stream().filter(e -> e.getKey().startsWith("SECURITY")).count());
}
private QueryResponse executeQuery(ModifiableSolrParams params, String user, String pass) throws IOException, SolrServerException {
SolrRequest req = new QueryRequest(params);
req.setBasicAuthCredentials(user, pass);
QueryResponse resp = (QueryResponse) req.process(cluster.getSolrClient(), COLLECTION);
assertNull(resp.getException());
assertEquals(0, resp.getStatus());
return resp;
}
private void addDocument(String user, String pass, String... fields) throws IOException, SolrServerException {
SolrInputDocument doc = new SolrInputDocument();
boolean isKey = true;
String key = null;
for (String field : fields) {
if (isKey) {
key = field;
isKey = false;
} else {
doc.setField(key, field);
}
}
UpdateRequest update = new UpdateRequest();
update.setBasicAuthCredentials(user, pass);
update.add(doc);
cluster.getSolrClient().request(update, COLLECTION);
update.commit(cluster.getSolrClient(), COLLECTION);
}
/** @see #executeCommand */
private static Map<String,Object> getAuthPlugins(String url) {
Map<String,Object> plugins = new HashMap<>();
if (url.endsWith("authentication")) {
for (JettySolrRunner r : cluster.getJettySolrRunners()) {
plugins.put(r.getNodeName(), r.getCoreContainer().getAuthenticationPlugin());
}
} else if (url.endsWith("authorization")) {
for (JettySolrRunner r : cluster.getJettySolrRunners()) {
plugins.put(r.getNodeName(), r.getCoreContainer().getAuthorizationPlugin());
}
} else {
fail("Test helper method assumptions broken: " + url);
}
return plugins;
}
public static void executeCommand(String url, HttpClient cl, String payload,
String user, String pwd) throws Exception {
// HACK: (attempted) work around for SOLR-13464...
//
// note the authz/authn objects in use on each node before executing the command,
// then wait until we see new objects on every node *after* executing the command
// before returning...
final Set<Map.Entry<String,Object>> initialPlugins = getAuthPlugins(url).entrySet();
HttpPost httpPost;
HttpResponse r;
httpPost = new HttpPost(url);
setAuthorizationHeader(httpPost, makeBasicAuthHeader(user, pwd));
httpPost.setEntity(new ByteArrayEntity(payload.getBytes(UTF_8)));
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
r = cl.execute(httpPost);
String response = IOUtils.toString(r.getEntity().getContent(), StandardCharsets.UTF_8);
assertEquals("Non-200 response code. Response was " + response, 200, r.getStatusLine().getStatusCode());
assertFalse("Response contained errors: " + response, response.contains("errorMessages"));
Utils.consumeFully(r.getEntity());
// HACK (continued)...
final TimeOut timeout = new TimeOut(10, TimeUnit.SECONDS, TimeSource.NANO_TIME);
timeout.waitFor("core containers never fully updated their auth plugins",
() -> {
final Set<Map.Entry<String,Object>> tmpSet = getAuthPlugins(url).entrySet();
tmpSet.retainAll(initialPlugins);
return tmpSet.isEmpty();
});
}
public static Replica getRandomReplica(DocCollection coll, Random random) {
ArrayList<Replica> l = new ArrayList<>();
for (Slice slice : coll.getSlices()) {
l.addAll(slice.getReplicas());
}
Collections.shuffle(l, random);
return l.isEmpty() ? null : l.get(0);
}
//the password is 'SolrRocks'
//this could be generated everytime. But , then we will not know if there is any regression
protected static final String STD_CONF = "{\n" +
" 'authentication':{\n" +
" 'class':'solr.BasicAuthPlugin',\n" +
" 'credentials':{'solr':'orwp2Ghgj39lmnrZOTm7Qtre1VqHFDfwAEzr0ApbN3Y= Ju5osoAqOX8iafhWpPP01E5P+sg8tK8tHON7rCYZRRw='}},\n" +
" 'authorization':{\n" +
" 'class':'solr.RuleBasedAuthorizationPlugin',\n" +
" 'user-role':{'solr':'admin'},\n" +
" 'permissions':[{'name':'security-edit','role':'admin'}]}}";
}
| solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.MetricRegistry;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.client.solrj.impl.HttpClientUtil;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.GenericSolrRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.RequestWriter.StringPayloadContentWriter;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.request.V2Request;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.cloud.SolrCloudAuthTestCase;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.Utils;
import org.apache.solr.util.SolrCLI;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonMap;
public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final String COLLECTION = "authCollection";
@Before
public void setupCluster() throws Exception {
configureCluster(3)
.addConfig("conf", configset("cloud-minimal"))
.configure();
CollectionAdminRequest.createCollection(COLLECTION, "conf", 3, 1).process(cluster.getSolrClient());
cluster.waitForActiveCollection(COLLECTION, 3, 3);
}
@After
public void tearDownCluster() throws Exception {
shutdownCluster();
}
@Test
//commented 9-Aug-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // 21-May-2018
// commented out on: 17-Feb-2019 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // annotated on: 24-Dec-2018
public void testBasicAuth() throws Exception {
boolean isUseV2Api = random().nextBoolean();
String authcPrefix = "/admin/authentication";
String authzPrefix = "/admin/authorization";
if(isUseV2Api){
authcPrefix = "/____v2/cluster/security/authentication";
authzPrefix = "/____v2/cluster/security/authorization";
}
NamedList<Object> rsp;
HttpClient cl = null;
try {
cl = HttpClientUtil.createClient(null);
JettySolrRunner randomJetty = cluster.getRandomJetty(random());
String baseUrl = randomJetty.getBaseUrl().toString();
verifySecurityStatus(cl, baseUrl + authcPrefix, "/errorMessages", null, 20);
zkClient().setData("/security.json", STD_CONF.replaceAll("'", "\"").getBytes(UTF_8), true);
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/class", "solr.BasicAuthPlugin", 20);
randomJetty.stop();
cluster.waitForJettyToStop(randomJetty);
randomJetty.start();
cluster.waitForAllNodes(30);
cluster.waitForActiveCollection(COLLECTION, 3, 3);
baseUrl = randomJetty.getBaseUrl().toString();
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/class", "solr.BasicAuthPlugin", 20);
assertNumberOfMetrics(16); // Basic auth metrics available
assertAuthMetricsMinimums(1, 0, 1, 0, 0, 0);
assertPkiAuthMetricsMinimums(0, 0, 0, 0, 0, 0);
String command = "{\n" +
"'set-user': {'harry':'HarryIsCool'}\n" +
"}";
final SolrRequest genericReq;
if (isUseV2Api) {
genericReq = new V2Request.Builder("/cluster/security/authentication")
.withPayload(command)
.withMethod(SolrRequest.METHOD.POST).build();
} else {
genericReq = new GenericSolrRequest(SolrRequest.METHOD.POST, authcPrefix, new ModifiableSolrParams());
((GenericSolrRequest)genericReq).setContentWriter(new StringPayloadContentWriter(command, CommonParams.JSON_MIME));
}
// avoid bad connection races due to shutdown
cluster.getSolrClient().getHttpClient().getConnectionManager().closeExpiredConnections();
cluster.getSolrClient().getHttpClient().getConnectionManager().closeIdleConnections(1, TimeUnit.MILLISECONDS);
HttpSolrClient.RemoteSolrException exp = expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
cluster.getSolrClient().request(genericReq);
});
assertEquals(401, exp.code());
assertAuthMetricsMinimums(2, 0, 2, 0, 0, 0);
assertPkiAuthMetricsMinimums(0, 0, 0, 0, 0, 0);
command = "{\n" +
"'set-user': {'harry':'HarryIsUberCool'}\n" +
"}";
HttpPost httpPost = new HttpPost(baseUrl + authcPrefix);
setAuthorizationHeader(httpPost, makeBasicAuthHeader("solr", "SolrRocks"));
httpPost.setEntity(new ByteArrayEntity(command.getBytes(UTF_8)));
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication.enabled", "true", 20);
HttpResponse r = cl.execute(httpPost);
int statusCode = r.getStatusLine().getStatusCode();
Utils.consumeFully(r.getEntity());
assertEquals("proper_cred sent, but access denied", 200, statusCode);
assertPkiAuthMetricsMinimums(0, 0, 0, 0, 0, 0);
assertAuthMetricsMinimums(4, 1, 3, 0, 0, 0);
baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/credentials/harry", NOT_NULL_PREDICATE, 20);
command = "{\n" +
"'set-user-role': {'harry':'admin'}\n" +
"}";
executeCommand(baseUrl + authzPrefix, cl,command, "solr", "SolrRocks");
assertAuthMetricsMinimums(5, 2, 3, 0, 0, 0);
Thread.sleep(2000); // sad little wait to try and avoid other clients from hitting http noresponse after jetty restart
baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
verifySecurityStatus(cl, baseUrl + authzPrefix, "authorization/user-role/harry", NOT_NULL_PREDICATE, 20);
executeCommand(baseUrl + authzPrefix, cl, Utils.toJSONString(singletonMap("set-permission", Utils.makeMap
("collection", "x",
"path", "/update/*",
"role", "dev"))), "harry", "HarryIsUberCool" );
verifySecurityStatus(cl, baseUrl + authzPrefix, "authorization/permissions[1]/collection", "x", 20);
assertAuthMetricsMinimums(8, 3, 5, 0, 0, 0);
executeCommand(baseUrl + authzPrefix, cl,Utils.toJSONString(singletonMap("set-permission", Utils.makeMap
("name", "collection-admin-edit", "role", "admin"))), "harry", "HarryIsUberCool" );
verifySecurityStatus(cl, baseUrl + authzPrefix, "authorization/permissions[2]/name", "collection-admin-edit", 20);
assertAuthMetricsMinimums(10, 4, 6, 0, 0, 0);
CollectionAdminRequest.Reload reload = CollectionAdminRequest.reloadCollection(COLLECTION);
try (HttpSolrClient solrClient = getHttpSolrClient(baseUrl)) {
expectThrows(HttpSolrClient.RemoteSolrException.class, () -> solrClient.request(reload));
reload.setMethod(SolrRequest.METHOD.POST);
expectThrows(HttpSolrClient.RemoteSolrException.class, () -> solrClient.request(reload));
}
cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION)
.setBasicAuthCredentials("harry", "HarryIsUberCool"));
expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION)
.setBasicAuthCredentials("harry", "Cool12345"));
});
assertAuthMetricsMinimums(14, 5, 8, 1, 0, 0);
executeCommand(baseUrl + authzPrefix, cl,"{set-permission : { name : update , role : admin}}", "harry", "HarryIsUberCool");
UpdateRequest del = new UpdateRequest().deleteByQuery("*:*");
del.setBasicAuthCredentials("harry","HarryIsUberCool");
del.setCommitWithin(10);
del.process(cluster.getSolrClient(), COLLECTION);
//Test for SOLR-12514. Create a new jetty . This jetty does not have the collection.
//Make a request to that jetty and it should fail
JettySolrRunner aNewJetty = cluster.startJettySolrRunner();
SolrClient aNewClient = aNewJetty.newClient();
UpdateRequest delQuery = null;
delQuery = new UpdateRequest().deleteByQuery("*:*");
delQuery.setBasicAuthCredentials("harry","HarryIsUberCool");
delQuery.process(aNewClient, COLLECTION);//this should succeed
try {
HttpSolrClient.RemoteSolrException e = expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
new UpdateRequest().deleteByQuery("*:*").process(aNewClient, COLLECTION);
});
assertTrue(e.getMessage().contains("Unauthorized request"));
} finally {
aNewClient.close();
cluster.stopJettySolrRunner(aNewJetty);
}
addDocument("harry","HarryIsUberCool","id", "4");
executeCommand(baseUrl + authcPrefix, cl, "{set-property : { blockUnknown: true}}", "harry", "HarryIsUberCool");
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/blockUnknown", "true", 20, "harry", "HarryIsUberCool");
verifySecurityStatus(cl, baseUrl + "/admin/info/key", "key", NOT_NULL_PREDICATE, 20);
assertAuthMetricsMinimums(17, 8, 8, 1, 0, 0);
String[] toolArgs = new String[]{
"status", "-solr", baseUrl};
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream stdoutSim = new PrintStream(baos, true, StandardCharsets.UTF_8.name());
SolrCLI.StatusTool tool = new SolrCLI.StatusTool(stdoutSim);
try {
System.setProperty("basicauth", "harry:HarryIsUberCool");
tool.runTool(SolrCLI.processCommandLineArgs(SolrCLI.joinCommonAndToolOptions(tool.getOptions()), toolArgs));
Map obj = (Map) Utils.fromJSON(new ByteArrayInputStream(baos.toByteArray()));
assertTrue(obj.containsKey("version"));
assertTrue(obj.containsKey("startTime"));
assertTrue(obj.containsKey("uptime"));
assertTrue(obj.containsKey("memory"));
} catch (Exception e) {
log.error("RunExampleTool failed due to: " + e +
"; stdout from tool prior to failure: " + baos.toString(StandardCharsets.UTF_8.name()));
}
SolrParams params = new MapSolrParams(Collections.singletonMap("q", "*:*"));
// Query that fails due to missing credentials
exp = expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
cluster.getSolrClient().query(COLLECTION, params);
});
assertEquals(401, exp.code());
assertAuthMetricsMinimums(19, 8, 8, 1, 2, 0);
assertPkiAuthMetricsMinimums(3, 3, 0, 0, 0, 0);
// Query that succeeds
GenericSolrRequest req = new GenericSolrRequest(SolrRequest.METHOD.GET, "/select", params);
req.setBasicAuthCredentials("harry", "HarryIsUberCool");
cluster.getSolrClient().request(req, COLLECTION);
assertAuthMetricsMinimums(20, 8, 8, 1, 2, 0);
assertPkiAuthMetricsMinimums(10, 10, 0, 0, 0, 0);
addDocument("harry","HarryIsUberCool","id", "5");
assertAuthMetricsMinimums(23, 11, 9, 1, 2, 0);
assertPkiAuthMetricsMinimums(14, 14, 0, 0, 0, 0);
// Reindex collection depends on streaming request that needs to authenticate against new collection
CollectionAdminRequest.ReindexCollection reindexReq = CollectionAdminRequest.reindexCollection(COLLECTION);
reindexReq.setBasicAuthCredentials("harry", "HarryIsUberCool");
cluster.getSolrClient().request(reindexReq, COLLECTION);
assertAuthMetricsMinimums(24, 12, 9, 1, 2, 0);
assertPkiAuthMetricsMinimums(15, 15, 0, 0, 0, 0);
// Validate forwardCredentials
assertEquals(1, executeQuery(params("q", "id:5"), "harry", "HarryIsUberCool").getResults().getNumFound());
assertAuthMetricsMinimums(25, 13, 9, 1, 2, 0);
assertPkiAuthMetricsMinimums(19, 19, 0, 0, 0, 0);
executeCommand(baseUrl + authcPrefix, cl, "{set-property : { forwardCredentials: true}}", "harry", "HarryIsUberCool");
verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/forwardCredentials", "true", 20, "harry", "HarryIsUberCool");
assertEquals(1, executeQuery(params("q", "id:5"), "harry", "HarryIsUberCool").getResults().getNumFound());
assertAuthMetricsMinimums(32, 20, 9, 1, 2, 0);
assertPkiAuthMetricsMinimums(19, 19, 0, 0, 0, 0);
executeCommand(baseUrl + authcPrefix, cl, "{set-property : { blockUnknown: false}}", "harry", "HarryIsUberCool");
} finally {
if (cl != null) {
HttpClientUtil.close(cl);
}
}
}
private void assertNumberOfMetrics(int num) {
MetricRegistry registry0 = cluster.getJettySolrRunner(0).getCoreContainer().getMetricManager().registry("solr.node");
assertNotNull(registry0);
assertEquals(num, registry0.getMetrics().entrySet().stream().filter(e -> e.getKey().startsWith("SECURITY")).count());
}
private QueryResponse executeQuery(ModifiableSolrParams params, String user, String pass) throws IOException, SolrServerException {
SolrRequest req = new QueryRequest(params);
req.setBasicAuthCredentials(user, pass);
QueryResponse resp = (QueryResponse) req.process(cluster.getSolrClient(), COLLECTION);
assertNull(resp.getException());
assertEquals(0, resp.getStatus());
return resp;
}
private void addDocument(String user, String pass, String... fields) throws IOException, SolrServerException {
SolrInputDocument doc = new SolrInputDocument();
boolean isKey = true;
String key = null;
for (String field : fields) {
if (isKey) {
key = field;
isKey = false;
} else {
doc.setField(key, field);
}
}
UpdateRequest update = new UpdateRequest();
update.setBasicAuthCredentials(user, pass);
update.add(doc);
cluster.getSolrClient().request(update, COLLECTION);
update.commit(cluster.getSolrClient(), COLLECTION);
}
public static void executeCommand(String url, HttpClient cl, String payload, String user, String pwd)
throws IOException {
HttpPost httpPost;
HttpResponse r;
httpPost = new HttpPost(url);
setAuthorizationHeader(httpPost, makeBasicAuthHeader(user, pwd));
httpPost.setEntity(new ByteArrayEntity(payload.getBytes(UTF_8)));
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
r = cl.execute(httpPost);
String response = IOUtils.toString(r.getEntity().getContent(), StandardCharsets.UTF_8);
assertEquals("Non-200 response code. Response was " + response, 200, r.getStatusLine().getStatusCode());
assertFalse("Response contained errors: " + response, response.contains("errorMessages"));
Utils.consumeFully(r.getEntity());
}
public static Replica getRandomReplica(DocCollection coll, Random random) {
ArrayList<Replica> l = new ArrayList<>();
for (Slice slice : coll.getSlices()) {
l.addAll(slice.getReplicas());
}
Collections.shuffle(l, random);
return l.isEmpty() ? null : l.get(0);
}
//the password is 'SolrRocks'
//this could be generated everytime. But , then we will not know if there is any regression
protected static final String STD_CONF = "{\n" +
" 'authentication':{\n" +
" 'class':'solr.BasicAuthPlugin',\n" +
" 'credentials':{'solr':'orwp2Ghgj39lmnrZOTm7Qtre1VqHFDfwAEzr0ApbN3Y= Ju5osoAqOX8iafhWpPP01E5P+sg8tK8tHON7rCYZRRw='}},\n" +
" 'authorization':{\n" +
" 'class':'solr.RuleBasedAuthorizationPlugin',\n" +
" 'user-role':{'solr':'admin'},\n" +
" 'permissions':[{'name':'security-edit','role':'admin'}]}}";
}
| Harden BasicAuthIntegrationTest w/work around for SOLR-13464
| solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.java | Harden BasicAuthIntegrationTest w/work around for SOLR-13464 |
|
Java | apache-2.0 | 995b32647fb2771b44b79e2eef5fbbe85498e6d1 | 0 | tadayosi/camel,christophd/camel,christophd/camel,cunningt/camel,adessaigne/camel,christophd/camel,apache/camel,cunningt/camel,tadayosi/camel,christophd/camel,adessaigne/camel,christophd/camel,apache/camel,apache/camel,apache/camel,tadayosi/camel,adessaigne/camel,tadayosi/camel,adessaigne/camel,apache/camel,cunningt/camel,adessaigne/camel,cunningt/camel,tadayosi/camel,adessaigne/camel,cunningt/camel,cunningt/camel,tadayosi/camel,apache/camel,christophd/camel | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.tika;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.xml.XMLConstants;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.apache.camel.Exchange;
import org.apache.camel.support.DefaultProducer;
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.Detector;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.ExpandedTitleContentHandler;
import org.apache.tika.sax.boilerpipe.BoilerpipeContentHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TikaProducer extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(TikaProducer.class);
private final TikaConfiguration tikaConfiguration;
private final Parser parser;
private final Detector detector;
private final String encoding;
public TikaProducer(TikaEndpoint endpoint) {
this(endpoint, null);
}
public TikaProducer(TikaEndpoint endpoint, Parser parser) {
super(endpoint);
this.tikaConfiguration = endpoint.getTikaConfiguration();
this.encoding = this.tikaConfiguration.getTikaParseOutputEncoding();
TikaConfig config = this.tikaConfiguration.getTikaConfig();
this.detector = config.getDetector();
if (parser == null) {
this.parser = new AutoDetectParser(this.tikaConfiguration.getTikaConfig());
} else {
this.parser = parser;
}
}
@Override
public void process(Exchange exchange) throws Exception {
TikaOperation operation = this.tikaConfiguration.getOperation();
Object result;
switch (operation) {
case detect:
result = doDetect(exchange);
break;
case parse:
result = doParse(exchange);
break;
default:
throw new IllegalArgumentException(String.format("Unknown operation %s", tikaConfiguration.getOperation()));
}
// propagate headers
exchange.getMessage().setHeaders(exchange.getIn().getHeaders());
// and set result
exchange.getMessage().setBody(result);
}
private Object doDetect(Exchange exchange) throws IOException {
MediaType result;
try (InputStream inputStream = exchange.getIn().getBody(InputStream.class)) {
Metadata metadata = new Metadata();
result = this.detector.detect(inputStream, metadata);
convertMetadataToHeaders(metadata, exchange);
}
return result.toString();
}
private Object doParse(Exchange exchange)
throws TikaException, IOException, SAXException, TransformerConfigurationException {
OutputStream result = new ByteArrayOutputStream();
try (InputStream inputStream = exchange.getIn().getBody(InputStream.class)) {
ContentHandler contentHandler = getContentHandler(this.tikaConfiguration, result);
ParseContext context = new ParseContext();
context.set(Parser.class, this.parser);
Metadata metadata = new Metadata();
this.parser.parse(inputStream, contentHandler, metadata, context);
convertMetadataToHeaders(metadata, exchange);
}
return result;
}
private void convertMetadataToHeaders(Metadata metadata, Exchange exchange) {
if (metadata != null) {
for (String metaname : metadata.names()) {
String[] values = metadata.getValues(metaname);
if (values.length == 1) {
exchange.getIn().setHeader(metaname, values[0]);
} else {
exchange.getIn().setHeader(metaname, values);
}
}
}
}
protected ContentHandler getContentHandler(TikaConfiguration configuration, OutputStream outputStream)
throws TransformerConfigurationException, UnsupportedEncodingException {
ContentHandler result = null;
TikaParseOutputFormat outputFormat = configuration.getTikaParseOutputFormat();
switch (outputFormat) {
case xml:
result = getTransformerHandler(outputStream, "xml", true);
break;
case text:
result = new BodyContentHandler(new OutputStreamWriter(outputStream, this.encoding));
break;
case textMain:
result = new BoilerpipeContentHandler(new OutputStreamWriter(outputStream, this.encoding));
break;
case html:
result = new ExpandedTitleContentHandler(getTransformerHandler(outputStream, "html", true));
break;
default:
throw new IllegalArgumentException(
String.format("Unknown format %s", tikaConfiguration.getTikaParseOutputFormat()));
}
return result;
}
private TransformerHandler getTransformerHandler(
OutputStream output, String method,
boolean prettyPrint)
throws TransformerConfigurationException, UnsupportedEncodingException {
SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
TransformerHandler handler = factory.newTransformerHandler();
handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
handler.getTransformer().setOutputProperty(OutputKeys.INDENT, prettyPrint ? "yes" : "no");
if (this.encoding != null) {
handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, this.encoding);
handler.setResult(new StreamResult(new OutputStreamWriter(output, this.encoding)));
} else {
LOG.error("encoding is null");
return null;
}
return handler;
}
}
| components/camel-tika/src/main/java/org/apache/camel/component/tika/TikaProducer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.tika;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.xml.XMLConstants;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.apache.camel.Exchange;
import org.apache.camel.support.DefaultProducer;
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.Detector;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.ExpandedTitleContentHandler;
import org.apache.tika.sax.boilerpipe.BoilerpipeContentHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TikaProducer extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(TikaProducer.class);
private final TikaConfiguration tikaConfiguration;
private final Parser parser;
private final Detector detector;
private final String encoding;
public TikaProducer(TikaEndpoint endpoint) {
this(endpoint, null);
}
public TikaProducer(TikaEndpoint endpoint, Parser parser) {
super(endpoint);
this.tikaConfiguration = endpoint.getTikaConfiguration();
this.encoding = this.tikaConfiguration.getTikaParseOutputEncoding();
TikaConfig config = this.tikaConfiguration.getTikaConfig();
this.detector = config.getDetector();
if (parser == null) {
this.parser = new AutoDetectParser(this.tikaConfiguration.getTikaConfig());
} else {
this.parser = parser;
}
}
@Override
public void process(Exchange exchange) throws Exception {
TikaOperation operation = this.tikaConfiguration.getOperation();
Object result;
switch (operation) {
case detect:
result = doDetect(exchange);
break;
case parse:
result = doParse(exchange);
break;
default:
throw new IllegalArgumentException(String.format("Unknown operation %s", tikaConfiguration.getOperation()));
}
// propagate headers
exchange.getMessage().setHeaders(exchange.getIn().getHeaders());
// and set result
exchange.getMessage().setBody(result);
}
private Object doDetect(Exchange exchange) throws IOException {
MediaType result;
try (InputStream inputStream = exchange.getIn().getBody(InputStream.class)) {
Metadata metadata = new Metadata();
result = this.detector.detect(inputStream, metadata);
convertMetadataToHeaders(metadata, exchange);
}
return result.toString();
}
private Object doParse(Exchange exchange)
throws TikaException, IOException, SAXException, TransformerConfigurationException {
OutputStream result = new ByteArrayOutputStream();
try (InputStream inputStream = exchange.getIn().getBody(InputStream.class)) {
ContentHandler contentHandler = getContentHandler(this.tikaConfiguration, result);
ParseContext context = new ParseContext();
context.set(Parser.class, this.parser);
Metadata metadata = new Metadata();
this.parser.parse(inputStream, contentHandler, metadata, context);
convertMetadataToHeaders(metadata, exchange);
}
return result;
}
private void convertMetadataToHeaders(Metadata metadata, Exchange exchange) {
if (metadata != null) {
for (String metaname : metadata.names()) {
String[] values = metadata.getValues(metaname);
if (values.length == 1) {
exchange.getIn().setHeader(metaname, values[0]);
} else {
exchange.getIn().setHeader(metaname, values);
}
}
}
}
private ContentHandler getContentHandler(TikaConfiguration configuration, OutputStream outputStream)
throws TransformerConfigurationException, UnsupportedEncodingException {
ContentHandler result = null;
TikaParseOutputFormat outputFormat = configuration.getTikaParseOutputFormat();
switch (outputFormat) {
case xml:
result = getTransformerHandler(outputStream, "xml", true);
break;
case text:
result = new BodyContentHandler(new OutputStreamWriter(outputStream, this.encoding));
break;
case textMain:
result = new BoilerpipeContentHandler(new OutputStreamWriter(outputStream, this.encoding));
break;
case html:
result = new ExpandedTitleContentHandler(getTransformerHandler(outputStream, "html", true));
break;
default:
throw new IllegalArgumentException(
String.format("Unknown format %s", tikaConfiguration.getTikaParseOutputFormat()));
}
return result;
}
private TransformerHandler getTransformerHandler(
OutputStream output, String method,
boolean prettyPrint)
throws TransformerConfigurationException, UnsupportedEncodingException {
SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
TransformerHandler handler = factory.newTransformerHandler();
handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
handler.getTransformer().setOutputProperty(OutputKeys.INDENT, prettyPrint ? "yes" : "no");
if (this.encoding != null) {
handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, this.encoding);
handler.setResult(new StreamResult(new OutputStreamWriter(output, this.encoding)));
} else {
LOG.error("encoding is null");
return null;
}
return handler;
}
}
| camel-tika: Make TikaProducer.getContentHandler protected so that it can be overridden
| components/camel-tika/src/main/java/org/apache/camel/component/tika/TikaProducer.java | camel-tika: Make TikaProducer.getContentHandler protected so that it can be overridden |
|
Java | apache-2.0 | e7ddb860fe067d58423f0a26e673ab9da552a060 | 0 | samthor/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,petteyg/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ibinti/intellij-community,jexp/idea2,asedunov/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,jexp/idea2,tmpgit/intellij-community,holmes/intellij-community,ryano144/intellij-community,fnouama/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,joewalnes/idea-community,fengbaicanhe/intellij-community,izonder/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,caot/intellij-community,caot/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,hurricup/intellij-community,semonte/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,caot/intellij-community,caot/intellij-community,apixandru/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,adedayo/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,samthor/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,jexp/idea2,lucafavatella/intellij-community,joewalnes/idea-community,asedunov/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,xfournet/intellij-community,retomerz/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,asedunov/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,caot/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,consulo/consulo,FHannes/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,caot/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,kool79/intellij-community,joewalnes/idea-community,vladmm/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,da1z/intellij-community,semonte/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,apixandru/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,samthor/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,adedayo/intellij-community,dslomov/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,supersven/intellij-community,samthor/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,slisson/intellij-community,da1z/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,da1z/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,hurricup/intellij-community,clumsy/intellij-community,supersven/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,ryano144/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,holmes/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,fitermay/intellij-community,jagguli/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,Distrotech/intellij-community,caot/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,signed/intellij-community,fitermay/intellij-community,asedunov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,jexp/idea2,idea4bsd/idea4bsd,signed/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,retomerz/intellij-community,semonte/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,jagguli/intellij-community,jagguli/intellij-community,supersven/intellij-community,asedunov/intellij-community,retomerz/intellij-community,signed/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,vladmm/intellij-community,holmes/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,signed/intellij-community,retomerz/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,youdonghai/intellij-community,signed/intellij-community,consulo/consulo,fnouama/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,fnouama/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,hurricup/intellij-community,consulo/consulo,ryano144/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,ryano144/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,da1z/intellij-community,ibinti/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ernestp/consulo,clumsy/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ibinti/intellij-community,hurricup/intellij-community,apixandru/intellij-community,samthor/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,izonder/intellij-community,amith01994/intellij-community,jagguli/intellij-community,jagguli/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,allotria/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,suncycheng/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,ernestp/consulo,ol-loginov/intellij-community,fnouama/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,caot/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,blademainer/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,signed/intellij-community,youdonghai/intellij-community,allotria/intellij-community,blademainer/intellij-community,holmes/intellij-community,apixandru/intellij-community,slisson/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,da1z/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,clumsy/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,asedunov/intellij-community,kool79/intellij-community,blademainer/intellij-community,robovm/robovm-studio,apixandru/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,apixandru/intellij-community,blademainer/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,izonder/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,ryano144/intellij-community,samthor/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,holmes/intellij-community,kdwink/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,supersven/intellij-community,robovm/robovm-studio,ryano144/intellij-community,izonder/intellij-community,slisson/intellij-community,ryano144/intellij-community,ibinti/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,fitermay/intellij-community,dslomov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,kool79/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,signed/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,amith01994/intellij-community,vladmm/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,holmes/intellij-community,dslomov/intellij-community,holmes/intellij-community,tmpgit/intellij-community,allotria/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,FHannes/intellij-community,adedayo/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,joewalnes/idea-community,robovm/robovm-studio,petteyg/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,slisson/intellij-community,suncycheng/intellij-community,da1z/intellij-community,kool79/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,jexp/idea2,idea4bsd/idea4bsd,orekyuu/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,consulo/consulo,amith01994/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,diorcety/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,signed/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,diorcety/intellij-community,clumsy/intellij-community,adedayo/intellij-community,petteyg/intellij-community,signed/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,diorcety/intellij-community,samthor/intellij-community,fitermay/intellij-community,consulo/consulo,vvv1559/intellij-community,retomerz/intellij-community,supersven/intellij-community,FHannes/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,caot/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,adedayo/intellij-community,blademainer/intellij-community,adedayo/intellij-community,kool79/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,dslomov/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,jexp/idea2,robovm/robovm-studio,fnouama/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,caot/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,slisson/intellij-community,samthor/intellij-community,youdonghai/intellij-community,slisson/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,joewalnes/idea-community,hurricup/intellij-community,xfournet/intellij-community,ernestp/consulo,dslomov/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,supersven/intellij-community,diorcety/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,semonte/intellij-community,signed/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,jexp/idea2,ernestp/consulo,mglukhikh/intellij-community,signed/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,semonte/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,xfournet/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community | package org.jetbrains.plugins.ruby.testing.testunit.runner.ui;
import com.intellij.execution.testframework.PoolOfTestIcons;
import com.intellij.execution.testframework.ui.TestsProgressAnimator;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.SimpleTextAttributes;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.ruby.testing.testunit.runner.BaseRUnitTestsTestCase;
import org.jetbrains.plugins.ruby.testing.testunit.runner.model.RTestUnitTestProxy;
import org.jetbrains.plugins.ruby.testing.testunit.runner.properties.RTestUnitConsoleProperties;
import javax.swing.*;
import java.util.ArrayList;
import java.text.NumberFormat;
/**
* @author Roman Chernyatchik
*/
public class TestsPresentationUtilTest extends BaseRUnitTestsTestCase {
@NonNls private static final String FAKE_TEST_NAME = "my test";
public void testProgressText() {
assertEquals("Running: 10 of 1 Failed: 1 ",
TestsPresentationUtil.getProgressStatus_Text(0, 0, 1, 10, 1));
assertEquals("Running: 10 of 1 ",
TestsPresentationUtil.getProgressStatus_Text(0, 0, 1, 10, 0));
//here number format is platform-dependent
assertEquals("Done: 10 of 0 Failed: 1 (" + NumberFormat.getInstance().format((double)5/1000.0) + " s) ",
TestsPresentationUtil.getProgressStatus_Text(0, 5, 0, 10, 1));
assertEquals("Done: 10 of 1 (0.0 s) ",
TestsPresentationUtil.getProgressStatus_Text(5, 5, 1, 10, 0));
}
public void testFormatTestProxyTest_NewTest() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.NOT_RAN, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_NewTestPaused() {
//paused
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(true);
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.NOT_RAN, renderer1.getIcon());
assertEquals(1, renderer1.getFragments().size());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_Started() {
//paused
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertIsAnimatorProgressIcon(renderer1.getIcon());
assertEquals(1, renderer1.getFragments().size());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_StartedAndPaused() {
//paused
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(true);
proxy1.setStarted();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(TestsProgressAnimator.PAUSED_ICON, renderer1.getIcon());
assertEquals(1, renderer1.getFragments().size());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_Passed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
proxy1.setFinished();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.PASSED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_Failed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
proxy1.setFailed();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.FAILED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
proxy1.setFinished();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.FAILED_ICON, renderer1.getIcon());
}
public void testFormatRootNodeWithChildren_Started() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
TestsPresentationUtil.formatRootNodeWithChildren(proxy1, renderer1);
assertIsAnimatorProgressIcon(renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Running tests...", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatRootNodeWithChildren_Failed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final RTestUnitTestProxy child = createTestProxy();
proxy1.addChild(child);
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
child.setStarted();
child.setFailed();
child.setFinished();
proxy1.setFailed();
TestsPresentationUtil.formatRootNodeWithChildren(proxy1, renderer1);
assertEquals(PoolOfTestIcons.FAILED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Test Results", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
final MyRenderer renderer2 = new MyRenderer(false);
TestsPresentationUtil.formatRootNodeWithChildren(proxy1, renderer2);
proxy1.setFinished();
assertEquals(PoolOfTestIcons.FAILED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Test Results", renderer1.getFragmentAt(0));
}
public void testFormatRootNodeWithChildren_Passed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final RTestUnitTestProxy child = createTestProxy();
proxy1.addChild(child);
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
child.setStarted();
child.setFinished();
proxy1.setFinished();
TestsPresentationUtil.formatRootNodeWithChildren(proxy1, renderer1);
assertEquals(PoolOfTestIcons.PASSED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Test Results", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatRootNodeWithoutChildren() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
TestsPresentationUtil.formatRootNodeWithoutChildren(proxy1, renderer1);
assertEquals(PoolOfTestIcons.NOT_RAN, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("No Test Results.", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.ERROR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatRootNodeWithoutChildren_Started() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
TestsPresentationUtil.formatRootNodeWithoutChildren(proxy1, renderer1);
assertIsAnimatorProgressIcon(renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Instantiating tests...", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatRootNodeWithoutChildren_Passed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
proxy1.setFinished();
TestsPresentationUtil.formatRootNodeWithoutChildren(proxy1, renderer1);
assertEquals(PoolOfTestIcons.PASSED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("All Tests Passed.", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
protected RTestUnitTestProxy createTestProxy() {
return new RTestUnitTestProxy(FAKE_TEST_NAME);
}
private void assertIsAnimatorProgressIcon(final Icon icon) {
for (Icon frame : TestsProgressAnimator.FRAMES) {
if (icon == frame) {
return;
}
}
fail("Icon isn't an Animator progress frame");
}
private class MyRenderer extends RTestUnitTestTreeRenderer {
private ListOfFragments myFragments;
public MyRenderer(final boolean isPaused) {
super(new RTestUnitConsoleProperties(createRTestsRunConfiguration()) {
@Override
public boolean isPaused() {
return isPaused;
}
});
myFragments = new ListOfFragments();
}
@Override
public void append(@NotNull @Nls final String fragment,
@NotNull final SimpleTextAttributes attributes,
final boolean isMainText) {
myFragments.add(fragment, attributes);
}
public ListOfFragments getFragments() {
return myFragments;
}
public String getFragmentAt(final int index) {
return myFragments.get(index).first;
}
public SimpleTextAttributes getAttribsAt(final int index) {
return myFragments.get(index).second;
}
}
private static class ListOfFragments extends ArrayList<Pair<String, SimpleTextAttributes>> {
public void add(@NotNull @Nls final String fragment, @NotNull final SimpleTextAttributes attributes) {
add(new Pair<String, SimpleTextAttributes>(fragment, attributes));
}
}
}
| plugins/ruby/testSrc/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/TestsPresentationUtilTest.java | package org.jetbrains.plugins.ruby.testing.testunit.runner.ui;
import com.intellij.execution.testframework.PoolOfTestIcons;
import com.intellij.execution.testframework.ui.TestsProgressAnimator;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.SimpleTextAttributes;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.ruby.testing.testunit.runner.BaseRUnitTestsTestCase;
import org.jetbrains.plugins.ruby.testing.testunit.runner.model.RTestUnitTestProxy;
import org.jetbrains.plugins.ruby.testing.testunit.runner.properties.RTestUnitConsoleProperties;
import javax.swing.*;
import java.util.ArrayList;
/**
* @author Roman Chernyatchik
*/
public class TestsPresentationUtilTest extends BaseRUnitTestsTestCase {
@NonNls private static final String FAKE_TEST_NAME = "my test";
public void testProgressText() {
assertEquals("Running: 10 of 1 Failed: 1 ",
TestsPresentationUtil.getProgressStatus_Text(0, 0, 1, 10, 1));
assertEquals("Running: 10 of 1 ",
TestsPresentationUtil.getProgressStatus_Text(0, 0, 1, 10, 0));
assertEquals("Done: 10 of 0 Failed: 1 (0.005 s) ",
TestsPresentationUtil.getProgressStatus_Text(0, 5, 0, 10, 1));
assertEquals("Done: 10 of 1 (0.0 s) ",
TestsPresentationUtil.getProgressStatus_Text(5, 5, 1, 10, 0));
}
public void testFormatTestProxyTest_NewTest() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.NOT_RAN, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_NewTestPaused() {
//paused
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(true);
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.NOT_RAN, renderer1.getIcon());
assertEquals(1, renderer1.getFragments().size());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_Started() {
//paused
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertIsAnimatorProgressIcon(renderer1.getIcon());
assertEquals(1, renderer1.getFragments().size());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_StartedAndPaused() {
//paused
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(true);
proxy1.setStarted();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(TestsProgressAnimator.PAUSED_ICON, renderer1.getIcon());
assertEquals(1, renderer1.getFragments().size());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_Passed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
proxy1.setFinished();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.PASSED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatTestProxyTest_Failed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
proxy1.setFailed();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.FAILED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals(FAKE_TEST_NAME, renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
proxy1.setFinished();
TestsPresentationUtil.formatTestProxy(proxy1, renderer1);
assertEquals(PoolOfTestIcons.FAILED_ICON, renderer1.getIcon());
}
public void testFormatRootNodeWithChildren_Started() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
TestsPresentationUtil.formatRootNodeWithChildren(proxy1, renderer1);
assertIsAnimatorProgressIcon(renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Running tests...", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatRootNodeWithChildren_Failed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final RTestUnitTestProxy child = createTestProxy();
proxy1.addChild(child);
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
child.setStarted();
child.setFailed();
child.setFinished();
proxy1.setFailed();
TestsPresentationUtil.formatRootNodeWithChildren(proxy1, renderer1);
assertEquals(PoolOfTestIcons.FAILED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Test Results", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
final MyRenderer renderer2 = new MyRenderer(false);
TestsPresentationUtil.formatRootNodeWithChildren(proxy1, renderer2);
proxy1.setFinished();
assertEquals(PoolOfTestIcons.FAILED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Test Results", renderer1.getFragmentAt(0));
}
public void testFormatRootNodeWithChildren_Passed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final RTestUnitTestProxy child = createTestProxy();
proxy1.addChild(child);
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
child.setStarted();
child.setFinished();
proxy1.setFinished();
TestsPresentationUtil.formatRootNodeWithChildren(proxy1, renderer1);
assertEquals(PoolOfTestIcons.PASSED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Test Results", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatRootNodeWithoutChildren() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
TestsPresentationUtil.formatRootNodeWithoutChildren(proxy1, renderer1);
assertEquals(PoolOfTestIcons.NOT_RAN, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("No Test Results.", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.ERROR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatRootNodeWithoutChildren_Started() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
TestsPresentationUtil.formatRootNodeWithoutChildren(proxy1, renderer1);
assertIsAnimatorProgressIcon(renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("Instantiating tests...", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
public void testFormatRootNodeWithoutChildren_Passed() {
final RTestUnitTestProxy proxy1 = createTestProxy();
final MyRenderer renderer1 = new MyRenderer(false);
proxy1.setStarted();
proxy1.setFinished();
TestsPresentationUtil.formatRootNodeWithoutChildren(proxy1, renderer1);
assertEquals(PoolOfTestIcons.PASSED_ICON, renderer1.getIcon());
assertOneElement(renderer1.getFragments());
assertEquals("All Tests Passed.", renderer1.getFragmentAt(0));
assertEquals(SimpleTextAttributes.REGULAR_ATTRIBUTES, renderer1.getAttribsAt(0));
}
protected RTestUnitTestProxy createTestProxy() {
return new RTestUnitTestProxy(FAKE_TEST_NAME);
}
private void assertIsAnimatorProgressIcon(final Icon icon) {
for (Icon frame : TestsProgressAnimator.FRAMES) {
if (icon == frame) {
return;
}
}
fail("Icon isn't an Animator progress frame");
}
private class MyRenderer extends RTestUnitTestTreeRenderer {
private ListOfFragments myFragments;
public MyRenderer(final boolean isPaused) {
super(new RTestUnitConsoleProperties(createRTestsRunConfiguration()) {
@Override
public boolean isPaused() {
return isPaused;
}
});
myFragments = new ListOfFragments();
}
@Override
public void append(@NotNull @Nls final String fragment,
@NotNull final SimpleTextAttributes attributes,
final boolean isMainText) {
myFragments.add(fragment, attributes);
}
public ListOfFragments getFragments() {
return myFragments;
}
public String getFragmentAt(final int index) {
return myFragments.get(index).first;
}
public SimpleTextAttributes getAttribsAt(final int index) {
return myFragments.get(index).second;
}
}
private static class ListOfFragments extends ArrayList<Pair<String, SimpleTextAttributes>> {
public void add(@NotNull @Nls final String fragment, @NotNull final SimpleTextAttributes attributes) {
add(new Pair<String, SimpleTextAttributes>(fragment, attributes));
}
}
}
| failing test TestsPresentationUtilTest was fixed
| plugins/ruby/testSrc/org/jetbrains/plugins/ruby/testing/testunit/runner/ui/TestsPresentationUtilTest.java | failing test TestsPresentationUtilTest was fixed |
|
Java | apache-2.0 | 239c7820c2e3a5de708ac21408469617d6d4070d | 0 | ol-loginov/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,caot/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,retomerz/intellij-community,ibinti/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,supersven/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,izonder/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,kdwink/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,holmes/intellij-community,signed/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,caot/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,kool79/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,Lekanich/intellij-community,izonder/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,dslomov/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,clumsy/intellij-community,jexp/idea2,asedunov/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,ryano144/intellij-community,dslomov/intellij-community,hurricup/intellij-community,apixandru/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,retomerz/intellij-community,asedunov/intellij-community,samthor/intellij-community,xfournet/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,apixandru/intellij-community,caot/intellij-community,hurricup/intellij-community,diorcety/intellij-community,slisson/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,jexp/idea2,da1z/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,signed/intellij-community,joewalnes/idea-community,holmes/intellij-community,caot/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,FHannes/intellij-community,izonder/intellij-community,izonder/intellij-community,diorcety/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,ibinti/intellij-community,supersven/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,retomerz/intellij-community,allotria/intellij-community,allotria/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,petteyg/intellij-community,caot/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,amith01994/intellij-community,blademainer/intellij-community,robovm/robovm-studio,diorcety/intellij-community,slisson/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,semonte/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,fitermay/intellij-community,kool79/intellij-community,FHannes/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,fnouama/intellij-community,allotria/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,jexp/idea2,amith01994/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,slisson/intellij-community,signed/intellij-community,tmpgit/intellij-community,caot/intellij-community,petteyg/intellij-community,diorcety/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,retomerz/intellij-community,ernestp/consulo,vladmm/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,allotria/intellij-community,xfournet/intellij-community,adedayo/intellij-community,fitermay/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,fitermay/intellij-community,consulo/consulo,youdonghai/intellij-community,ftomassetti/intellij-community,signed/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,izonder/intellij-community,ibinti/intellij-community,jexp/idea2,akosyakov/intellij-community,kool79/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,consulo/consulo,salguarnieri/intellij-community,joewalnes/idea-community,blademainer/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,ibinti/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ernestp/consulo,SerCeMan/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,kdwink/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,diorcety/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,holmes/intellij-community,samthor/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,holmes/intellij-community,ernestp/consulo,ibinti/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,retomerz/intellij-community,petteyg/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,vladmm/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,diorcety/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,signed/intellij-community,caot/intellij-community,samthor/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,supersven/intellij-community,youdonghai/intellij-community,supersven/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,diorcety/intellij-community,samthor/intellij-community,FHannes/intellij-community,caot/intellij-community,ahb0327/intellij-community,caot/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,caot/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,ryano144/intellij-community,holmes/intellij-community,joewalnes/idea-community,allotria/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,semonte/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,consulo/consulo,blademainer/intellij-community,alphafoobar/intellij-community,caot/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,vladmm/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,signed/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,semonte/intellij-community,orekyuu/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,slisson/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,signed/intellij-community,kdwink/intellij-community,jexp/idea2,amith01994/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,holmes/intellij-community,petteyg/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,amith01994/intellij-community,fnouama/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,signed/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,jexp/idea2,asedunov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,da1z/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ftomassetti/intellij-community,consulo/consulo,adedayo/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,ryano144/intellij-community,ryano144/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,signed/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,adedayo/intellij-community,signed/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ibinti/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,izonder/intellij-community,semonte/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,dslomov/intellij-community,signed/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,jagguli/intellij-community,robovm/robovm-studio,kool79/intellij-community,FHannes/intellij-community,caot/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,allotria/intellij-community,supersven/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,supersven/intellij-community,hurricup/intellij-community,kdwink/intellij-community,samthor/intellij-community,supersven/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,samthor/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,clumsy/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,da1z/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,gnuhub/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,allotria/intellij-community,izonder/intellij-community,da1z/intellij-community,jexp/idea2,wreckJ/intellij-community,diorcety/intellij-community,holmes/intellij-community,hurricup/intellij-community,diorcety/intellij-community,fnouama/intellij-community,da1z/intellij-community,signed/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,allotria/intellij-community,joewalnes/idea-community,consulo/consulo,asedunov/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,ernestp/consulo,Distrotech/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,asedunov/intellij-community,retomerz/intellij-community,joewalnes/idea-community,hurricup/intellij-community,FHannes/intellij-community,fnouama/intellij-community,allotria/intellij-community,asedunov/intellij-community,kdwink/intellij-community,vladmm/intellij-community,fitermay/intellij-community,kdwink/intellij-community,fitermay/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,izonder/intellij-community,kool79/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,clumsy/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,da1z/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,fnouama/intellij-community | /*
* Copyright 2000-2007 JetBrains s.r.o.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.actions;
import com.intellij.CommonBundle;
import com.intellij.ide.IdeView;
import com.intellij.ide.actions.CreateElementActionBase;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.config.GroovyGrailsConfiguration;
import javax.swing.*;
public abstract class NewActionBase extends CreateElementActionBase {
public NewActionBase(String text, String description, Icon icon) {
super(text, description, icon);
}
@NotNull
protected final PsiElement[] invokeDialog(final Project project, final PsiDirectory directory) {
MyInputValidator validator = new MyInputValidator(project, directory);
Messages.showInputDialog(project, getDialogPrompt(), getDialogTitle(), Messages.getQuestionIcon(), "", validator);
return validator.getCreatedElements();
}
protected abstract String getDialogPrompt();
protected abstract String getDialogTitle();
public void update(final AnActionEvent e) {
final Presentation presentation = e.getPresentation();
super.update(e);
if (!presentation.isEnabled() || !isUnderSourceRoots(e) || !isGroovyConfigured(e)) {
presentation.setEnabled(false);
presentation.setVisible(false);
}
}
public static boolean isGroovyConfigured(AnActionEvent e) {
Project project = (Project) e.getDataContext().getData(DataConstants.PROJECT);
if (project != null) {
PsiPackage groovyPackage = PsiManager.getInstance(project).findPackage("groovy.lang");
if (groovyPackage != null) return true;
}
return false;
}
public static boolean isUnderSourceRoots(final AnActionEvent e) {
final DataContext context = e.getDataContext();
Module module = (Module) context.getData(DataConstants.MODULE);
if (!GroovyGrailsConfiguration.isSuitableModule(module)) {
return false;
}
final IdeView view = (IdeView) context.getData(DataConstants.IDE_VIEW);
final Project project = (Project) context.getData(DataConstants.PROJECT);
if (view != null && project != null) {
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
PsiDirectory[] dirs = view.getDirectories();
for (PsiDirectory dir : dirs) {
if (projectFileIndex.isInSourceContent(dir.getVirtualFile()) && dir.getPackage() != null) {
return true;
}
}
}
return false;
}
@NotNull
protected PsiElement[] create(String newName, PsiDirectory directory) throws Exception {
return doCreate(newName, directory);
}
@NotNull
protected abstract PsiElement[] doCreate(String newName, PsiDirectory directory) throws Exception;
protected static PsiFile createClassFromTemplate(final PsiDirectory directory, String className, String templateName,
@NonNls String... parameters) throws IncorrectOperationException {
return GroovyTemplatesFactory.createFromTemplate(directory, className, className + ".groovy", templateName, parameters);
}
protected String getErrorTitle() {
return CommonBundle.getErrorTitle();
}
protected String getActionName(PsiDirectory directory, String newName) {
return GroovyBundle.message("newclass.progress.text", newName);
}
protected void checkBeforeCreate(String newName, PsiDirectory directory) throws IncorrectOperationException {
directory.checkCreateClass(newName);
}
}
| plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewActionBase.java | /*
* Copyright 2000-2007 JetBrains s.r.o.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.actions;
import com.intellij.CommonBundle;
import com.intellij.ide.IdeView;
import com.intellij.ide.actions.CreateElementActionBase;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.GroovyBundle;
import javax.swing.*;
public abstract class NewActionBase extends CreateElementActionBase {
public NewActionBase(String text, String description, Icon icon) {
super(text, description, icon);
}
@NotNull
protected final PsiElement[] invokeDialog(final Project project, final PsiDirectory directory) {
MyInputValidator validator = new MyInputValidator(project, directory);
Messages.showInputDialog(project, getDialogPrompt(), getDialogTitle(), Messages.getQuestionIcon(), "", validator);
return validator.getCreatedElements();
}
protected abstract String getDialogPrompt();
protected abstract String getDialogTitle();
public void update(final AnActionEvent e) {
final Presentation presentation = e.getPresentation();
super.update(e);
if (!presentation.isEnabled() || !isUnderSourceRoots(e))
return;
if (!isGroovyConfigured(e)) {
presentation.setEnabled(false);
presentation.setVisible(false);
}
}
protected boolean isGroovyConfigured(AnActionEvent e) {
Project project = (Project) e.getDataContext().getData(DataConstants.PROJECT);
if (project != null) {
PsiPackage groovyPackage = PsiManager.getInstance(project).findPackage("groovy.lang");
if (groovyPackage != null) return true;
}
return false;
}
public static boolean isUnderSourceRoots(final AnActionEvent e) {
final DataContext context = e.getDataContext();
Module module = (Module) context.getData(DataConstants.MODULE);
if (module == null) {
return false;
}
final IdeView view = (IdeView) context.getData(DataConstants.IDE_VIEW);
final Project project = (Project) context.getData(DataConstants.PROJECT);
if (view != null && project != null) {
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
PsiDirectory[] dirs = view.getDirectories();
for (PsiDirectory dir : dirs) {
if (projectFileIndex.isInSourceContent(dir.getVirtualFile()) && dir.getPackage() != null) {
return true;
}
}
}
return false;
}
@NotNull
protected PsiElement[] create(String newName, PsiDirectory directory) throws Exception {
return doCreate(newName, directory);
}
@NotNull
protected abstract PsiElement[] doCreate(String newName, PsiDirectory directory) throws Exception;
protected static PsiFile createClassFromTemplate(final PsiDirectory directory, String className, String templateName,
@NonNls String... parameters) throws IncorrectOperationException {
return GroovyTemplatesFactory.createFromTemplate(directory, className, className + ".groovy", templateName, parameters);
}
protected String getErrorTitle() {
return CommonBundle.getErrorTitle();
}
protected String getActionName(PsiDirectory directory, String newName) {
return GroovyBundle.message("newclass.progress.text", newName);
}
protected void checkBeforeCreate(String newName, PsiDirectory directory) throws IncorrectOperationException {
directory.checkCreateClass(newName);
}
}
| GRVY-649 | plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewActionBase.java | GRVY-649 |
|
Java | apache-2.0 | 7b3cfb2abe35c93f4eeeed6ec04cf2121d65110c | 0 | jnidzwetzki/bboxdb,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb,jnidzwetzki/scalephant,jnidzwetzki/scalephant | package de.fernunihagen.dna.jkn.scalephant.distribution;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.fernunihagen.dna.jkn.scalephant.ScalephantService;
import de.fernunihagen.dna.jkn.scalephant.distribution.membership.DistributedInstance;
import de.fernunihagen.dna.jkn.scalephant.distribution.membership.DistributedInstanceManager;
public class ZookeeperClient implements ScalephantService, Watcher {
/**
* The list of the zookeeper hosts
*/
protected final Collection<String> zookeeperHosts;
/**
* The name of the scalephant cluster
*/
protected final String clustername;
/**
* The zookeeper client instance
*/
protected ZooKeeper zookeeper;
/**
* The name of the instance
*/
protected String instancename = null;
/**
* The timeout for the zookeeper session
*/
protected final static int DEFAULT_TIMEOUT = 3000;
/**
* The prefix for nodes in sequential queues
*/
protected final static String SEQUENCE_QUEUE_PREFIX = "id-";
/**
* Name of the left tree node
*/
protected final static String NODE_LEFT = "left";
/**
* Name of the right tree node
*/
protected final static String NODE_RIGHT = "right";
/**
* Name of the split node
*/
protected final static String NAME_SPLIT = "split";
/**
* Name of the name prefix node
*/
protected final static String NAME_NAMEPREFIX = "nameprefix";
/**
* Name of the name prefix queue
*/
protected static final String NAME_PREFIXQUEUE = "nameprefixqueue";
/**
* Name of the replication node
*/
protected final static String NAME_REPLICATION = "replication";
/**
* The logger
*/
private final static Logger logger = LoggerFactory.getLogger(ZookeeperClient.class);
public ZookeeperClient(final Collection<String> zookeeperHosts, final String clustername) {
super();
this.zookeeperHosts = zookeeperHosts;
this.clustername = clustername;
}
/**
* Connect to zookeeper
*/
@Override
public void init() {
if(zookeeperHosts == null || zookeeperHosts.isEmpty()) {
logger.warn("No Zookeeper hosts are defined, not connecting to zookeeper");
return;
}
try {
zookeeper = new ZooKeeper(generateConnectString(), DEFAULT_TIMEOUT, this);
createDirectoryStructureIfNeeded();
if(instancename != null) {
registerInstance();
}
readMembershipAndRegisterWatch();
} catch (Exception e) {
logger.warn("Got exception while connecting to zookeeper", e);
}
}
/**
* Disconnect from zookeeper
*/
@Override
public void shutdown() {
if(zookeeper != null) {
try {
zookeeper.close();
} catch (InterruptedException e) {
logger.warn("Got exception while closing zookeeper connection", e);
}
zookeeper = null;
}
}
/**
* Register a watch on membership changes. A watch is a one-time operation, the watch
* is reregistered on each method call.
*/
protected void readMembershipAndRegisterWatch() {
try {
final List<String> instances = zookeeper.getChildren(getNodesPath(clustername), this);
final DistributedInstanceManager distributedInstanceManager = DistributedInstanceManager.getInstance();
final Set<DistributedInstance> instanceSet = new HashSet<DistributedInstance>();
for(final String member : instances) {
instanceSet.add(new DistributedInstance(member));
}
distributedInstanceManager.updateInstanceList(instanceSet);
} catch (KeeperException | InterruptedException e) {
logger.warn("Unable to read membership and create a watch", e);
}
}
/**
* Build a comma separated list of the zookeeper nodes
* @return
*/
protected String generateConnectString() {
// No zookeeper hosts are defined
if(zookeeperHosts == null) {
logger.warn("No zookeeper hosts are defined");
return "";
}
final StringBuilder sb = new StringBuilder();
for(final String zookeeperHost : zookeeperHosts) {
if(sb.length() != 0) {
sb.append(",");
}
sb.append(zookeeperHost);
}
return sb.toString();
}
/**
* Zookeeper watched event
*/
@Override
public void process(final WatchedEvent watchedEvent) {
logger.debug("Got zookeeper event: " + watchedEvent);
// Ignore null parameter
if(watchedEvent == null) {
logger.warn("process called with an null argument");
return;
}
// Ignore type=none event
if(watchedEvent.getType() == EventType.None) {
return;
}
// Process events
if(watchedEvent.getPath() != null) {
if(watchedEvent.getPath().equals(getNodesPath(clustername))) {
readMembershipAndRegisterWatch();
}
} else {
logger.warn("Got unknown zookeeper event: " + watchedEvent);
}
}
/**
* Register this instance of the scalephant
* @param clustername
* @param ownInstanceName
*/
public void registerScalephantInstanceAfterConnect(final String ownInstanceName) {
this.instancename = ownInstanceName;
}
/**
* Register the scalephant instance
* @throws ZookeeperException
* @throws InterruptedException
* @throws KeeperException
*/
protected void registerInstance() throws ZookeeperException {
final String instanceZookeeperPath = getNodesPath(clustername) + "/" + instancename;
logger.info("Register instance on: " + instanceZookeeperPath);
try {
zookeeper.create(instanceZookeeperPath,
"".getBytes(),
ZooDefs.Ids.READ_ACL_UNSAFE,
CreateMode.EPHEMERAL);
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Register the name of the cluster in the zookeeper directory
* @throws ZookeeperException
* @throws KeeperException
* @throws InterruptedException
*/
protected void createDirectoryStructureIfNeeded() throws ZookeeperException {
// /clusterpath/nodes - Node membership
final String nodesPath = getNodesPath(clustername);
createDirectoryStructureRecursive(nodesPath);
}
/**
* Get the path of the zookeeper clustername
* @param clustername
* @return
*/
protected String getClusterPath() {
return "/" + clustername;
}
/**
* Get the path of the zookeeper nodes
* @param clustername
* @return
*/
protected String getNodesPath(final String clustername) {
return getClusterPath() + "/nodes";
}
/**
* Get the path for the distribution group id queue
* @param distributionGroup
* @return
*/
protected String getDistributionGroupIdQueuePath(final String distributionGroup) {
return getDistributionGroupPath(distributionGroup) + "/" + NAME_PREFIXQUEUE;
}
/**
* Get the path for the distribution group
* @param distributionGroup
* @return
*/
protected String getDistributionGroupPath(final String distributionGroup) {
return getClusterPath() + "/" + distributionGroup;
}
@Override
public String getServicename() {
return "Zookeeper Client";
}
/**
* Create the given directory structure recursive
* @param path
* @throws ZookeeperException
*/
protected void createDirectoryStructureRecursive(final String path) throws ZookeeperException {
try {
// Does the full path already exists?
if(zookeeper.exists(path, this) != null) {
return;
}
// Otherwise check and create all sub paths
final String[] allNodes = path.split("/");
final StringBuilder sb = new StringBuilder();
// Start by 1 to skip the initial /
for (int i = 1; i < allNodes.length; i++) {
final String nextNode = allNodes[i];
sb.append("/");
sb.append(nextNode);
final String partialPath = sb.toString();
if(zookeeper.exists(partialPath, this) == null) {
logger.info(partialPath + " not found, creating");
zookeeper.create(partialPath,
"".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
}
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Get the next table id for a given distribution group
* @return
* @throws ZookeeperException
*/
public int getNextTableIdForDistributionGroup(final String distributionGroup) throws ZookeeperException {
final String distributionGroupIdQueuePath = getDistributionGroupIdQueuePath(distributionGroup);
createDirectoryStructureRecursive(distributionGroupIdQueuePath);
try {
final String nodename = zookeeper.create(distributionGroupIdQueuePath + "/" + SEQUENCE_QUEUE_PREFIX,
"".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT_SEQUENTIAL);
// Garbage collect the old child nodes
doIdQueueGarbageCollection(distributionGroupIdQueuePath);
// id-0000000063
// Element 0: id-
// Element 1: The number of the node
final String[] splittedName = nodename.split(SEQUENCE_QUEUE_PREFIX);
try {
return Integer.parseInt(splittedName[1]);
} catch(NumberFormatException e) {
logger.warn("Unable to parse number: " + splittedName[1], e);
throw new ZookeeperException(e);
}
} catch(InterruptedException | KeeperException e) {
throw new ZookeeperException(e);
}
}
/**
* Delete the old and unused child nodes for a given ID queue
* @param distributionGroupIdQueuePath
* @throws KeeperException
* @throws InterruptedException
*/
protected void doIdQueueGarbageCollection(final String distributionGroupIdQueuePath) throws KeeperException, InterruptedException {
final Random random = new Random(System.currentTimeMillis());
// 10 % garbage collection calls, 90% nop method calls
if((random.nextInt() % 100) > 90) {
logger.debug("Executing garbage collection on path: " + distributionGroupIdQueuePath);
final List<String> childs = zookeeper.getChildren(distributionGroupIdQueuePath, false);
for (Iterator<String> iterator = childs.iterator(); iterator.hasNext();) {
final String nodeName = iterator.next();
zookeeper.delete(distributionGroupIdQueuePath + "/" + nodeName, -1);
}
}
}
/**
* Read the structure of a distribution group
* @return
* @throws ZookeeperException
*/
public DistributionRegion readDistributionGroup(final String distributionGroup) throws ZookeeperException {
try {
final DistributionRegion root = DistributionRegion.createRootRegion(distributionGroup);
final String path = getDistributionGroupPath(distributionGroup);
readDistributionGroupRecursive(path, root);
return root;
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Read the distribution group in a recursive way
* @param path
* @param child
* @throws InterruptedException
* @throws KeeperException
*/
protected void readDistributionGroupRecursive(final String path, final DistributionRegion child) throws KeeperException, InterruptedException {
final String splitPathName = path + "/" + NAME_SPLIT;
if(zookeeper.exists(splitPathName, this) == null) {
return;
}
final byte[] bytes = zookeeper.getData(splitPathName, false, null);
final float splitFloat = Float.parseFloat(new String(bytes));
child.setSplit(splitFloat);
readDistributionGroupRecursive(path + "/" + NODE_LEFT, child.getLeftChild());
readDistributionGroupRecursive(path + "/" + NODE_RIGHT, child.getRightChild());
}
/**
* Delete the node recursive
* @param path
* @throws KeeperException
* @throws InterruptedException
*/
protected void deleteNodesRecursive(final String path) throws InterruptedException, KeeperException {
final List<String> childs = zookeeper.getChildren(path, false);
for(final String child: childs) {
deleteNodesRecursive(path + "/"+ child);
}
zookeeper.delete(path, -1);
}
/**
* Create a new distribution group
* @param distributionGroup
* @param replicationFactor
* @throws ZookeeperException
*/
public void createDistributionGroup(final String distributionGroup, final short replicationFactor) throws ZookeeperException {
try {
final String path = getDistributionGroupPath(distributionGroup);
zookeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
final int nameprefix = getNextTableIdForDistributionGroup(distributionGroup);
zookeeper.create(path + "/" + NAME_NAMEPREFIX, Integer.toString(nameprefix).getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zookeeper.create(path + "/" + NAME_REPLICATION, Short.toString(replicationFactor).getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Delete an existing distribution group
* @param distributionGroup
* @throws ZookeeperException
*/
public void deleteDistributionGroup(final String distributionGroup) throws ZookeeperException {
try {
final String path = getDistributionGroupPath(distributionGroup);
// Does the path not exist? We are done!
if(zookeeper.exists(path, this) == null) {
return;
}
deleteNodesRecursive(path);
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* List all existing distribution groups
* @return
* @throws ZookeeperException
*/
public List<DistributionGroupName> getDistributionGroups() throws ZookeeperException {
try {
final List<DistributionGroupName> groups = new ArrayList<DistributionGroupName>();
final String clusterPath = getClusterPath();
final List<String> nodes = zookeeper.getChildren(clusterPath, false);
for(final String node : nodes) {
final DistributionGroupName groupName = new DistributionGroupName(node);
if(groupName.isValid()) {
groups.add(groupName);
} else {
logger.warn("Got invalid distribution group name from zookeeper: " + groupName);
}
}
return groups;
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Get the replication factor for a distribution group
* @param distributionGroup
* @return
* @throws ZookeeperException
*/
public short getReplicationFactorForDistributionGroup(final String distributionGroup) throws ZookeeperException {
try {
final String path = getDistributionGroupPath(distributionGroup);
final String fullPath = path + "/" + NAME_REPLICATION;
final byte[] data = zookeeper.getData(fullPath, false, null);
try {
return Short.parseShort(new String(data));
} catch (NumberFormatException e) {
throw new ZookeeperException("Unable to parse replication factor: " + data + " for " + fullPath);
}
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Update zookeeper after splitting an region
* @param distributionRegion
* @throws ZookeeperException
*/
public void updateSplit(final DistributionRegion distributionRegion) throws ZookeeperException {
try {
final String zookeeperPath = getZookeeperPathForDistributionRegion(distributionRegion);
zookeeper.create(zookeeperPath + "/" + NAME_SPLIT, "".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// Left child
final String leftPath = zookeeperPath + "/" + NODE_LEFT;
zookeeper.create(leftPath, "".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
final int leftNamePrefix = getNextTableIdForDistributionGroup(distributionRegion.getName());
zookeeper.create(leftPath + "/" + NAME_NAMEPREFIX, Integer.toString(leftNamePrefix).getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// Right child
final String rightPath = zookeeperPath + "/" + NODE_RIGHT;
zookeeper.create(rightPath, "".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
final int rightNamePrefix = getNextTableIdForDistributionGroup(distributionRegion.getName());
zookeeper.create(rightPath + "/" + NAME_NAMEPREFIX, Integer.toString(rightNamePrefix).getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Get the zookeeper path for a distribution region
* @param distributionRegion
* @return
*/
protected String getZookeeperPathForDistributionRegion(final DistributionRegion distributionRegion) {
final String name = distributionRegion.getName();
final StringBuilder sb = new StringBuilder();
DistributionRegion tmpRegion = distributionRegion;
while(tmpRegion.getRootRegion() != null) {
if(tmpRegion.isLeftChild()) {
sb.insert(0, "/" + NODE_LEFT);
} else {
sb.insert(0, "/" + NODE_RIGHT);
}
tmpRegion = tmpRegion.getRootRegion();
}
sb.insert(0, getDistributionGroupPath(name));
return sb.toString();
}
}
| src/main/java/de/fernunihagen/dna/jkn/scalephant/distribution/ZookeeperClient.java | package de.fernunihagen.dna.jkn.scalephant.distribution;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.fernunihagen.dna.jkn.scalephant.ScalephantService;
import de.fernunihagen.dna.jkn.scalephant.distribution.membership.DistributedInstance;
import de.fernunihagen.dna.jkn.scalephant.distribution.membership.DistributedInstanceManager;
public class ZookeeperClient implements ScalephantService, Watcher {
/**
* The list of the zookeeper hosts
*/
protected final Collection<String> zookeeperHosts;
/**
* The name of the scalephant cluster
*/
protected final String clustername;
/**
* The zookeeper client instance
*/
protected ZooKeeper zookeeper;
/**
* The name of the instance
*/
protected String instancename = null;
/**
* The timeout for the zookeeper session
*/
protected final static int DEFAULT_TIMEOUT = 3000;
/**
* The prefix for nodes in sequential queues
*/
protected final static String SEQUENCE_QUEUE_PREFIX = "id-";
/**
* Name of the left tree node
*/
protected final static String NODE_LEFT = "left";
/**
* Name of the right tree node
*/
protected final static String NODE_RIGHT = "right";
/**
* Name of the split node
*/
protected final static String NAME_SPLIT = "split";
/**
* Name of the name prefix node
*/
protected final static String NAME_NAMEPREFIX = "nameprefix";
/**
* Name of the name prefix queue
*/
protected static final String NAME_PREFIXQUEUE = "nameprefixqueue";
/**
* Name of the replication node
*/
protected final static String NAME_REPLICATION = "replication";
/**
* The logger
*/
private final static Logger logger = LoggerFactory.getLogger(ZookeeperClient.class);
public ZookeeperClient(final Collection<String> zookeeperHosts, final String clustername) {
super();
this.zookeeperHosts = zookeeperHosts;
this.clustername = clustername;
}
/**
* Connect to zookeeper
*/
@Override
public void init() {
if(zookeeperHosts == null || zookeeperHosts.isEmpty()) {
logger.warn("No Zookeeper hosts are defined, not connecting to zookeeper");
return;
}
try {
zookeeper = new ZooKeeper(generateConnectString(), DEFAULT_TIMEOUT, this);
createDirectoryStructureIfNeeded();
if(instancename != null) {
registerInstance();
}
readMembershipAndRegisterWatch();
} catch (Exception e) {
logger.warn("Got exception while connecting to zookeeper", e);
}
}
/**
* Disconnect from zookeeper
*/
@Override
public void shutdown() {
if(zookeeper != null) {
try {
zookeeper.close();
} catch (InterruptedException e) {
logger.warn("Got exception while closing zookeeper connection", e);
}
zookeeper = null;
}
}
/**
* Register a watch on membership changes. A watch is a one-time operation, the watch
* is reregistered on each method call.
*/
protected void readMembershipAndRegisterWatch() {
try {
final List<String> instances = zookeeper.getChildren(getNodesPath(clustername), this);
final DistributedInstanceManager distributedInstanceManager = DistributedInstanceManager.getInstance();
final Set<DistributedInstance> instanceSet = new HashSet<DistributedInstance>();
for(final String member : instances) {
instanceSet.add(new DistributedInstance(member));
}
distributedInstanceManager.updateInstanceList(instanceSet);
} catch (KeeperException | InterruptedException e) {
logger.warn("Unable to read membership and create a watch", e);
}
}
/**
* Build a comma separated list of the zookeeper nodes
* @return
*/
protected String generateConnectString() {
// No zookeeper hosts are defined
if(zookeeperHosts == null) {
logger.warn("No zookeeper hosts are defined");
return "";
}
final StringBuilder sb = new StringBuilder();
for(final String zookeeperHost : zookeeperHosts) {
if(sb.length() != 0) {
sb.append(",");
}
sb.append(zookeeperHost);
}
return sb.toString();
}
/**
* Zookeeper watched event
*/
@Override
public void process(final WatchedEvent watchedEvent) {
logger.debug("Got zookeeper event: " + watchedEvent);
// Ignore null parameter
if(watchedEvent == null) {
logger.warn("process called with an null argument");
return;
}
// Ignore type=none event
if(watchedEvent.getType() == EventType.None) {
return;
}
// Process events
if(watchedEvent.getPath() != null) {
if(watchedEvent.getPath().equals(getNodesPath(clustername))) {
readMembershipAndRegisterWatch();
}
} else {
logger.warn("Got unknown zookeeper event: " + watchedEvent);
}
}
/**
* Register this instance of the scalephant
* @param clustername
* @param ownInstanceName
*/
public void registerScalephantInstanceAfterConnect(final String ownInstanceName) {
this.instancename = ownInstanceName;
}
/**
* Register the scalephant instance
* @throws ZookeeperException
* @throws InterruptedException
* @throws KeeperException
*/
protected void registerInstance() throws ZookeeperException {
final String instanceZookeeperPath = getNodesPath(clustername) + "/" + instancename;
logger.info("Register instance on: " + instanceZookeeperPath);
try {
zookeeper.create(instanceZookeeperPath,
"".getBytes(),
ZooDefs.Ids.READ_ACL_UNSAFE,
CreateMode.EPHEMERAL);
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Register the name of the cluster in the zookeeper directory
* @throws ZookeeperException
* @throws KeeperException
* @throws InterruptedException
*/
protected void createDirectoryStructureIfNeeded() throws ZookeeperException {
// /clusterpath/nodes - Node membership
final String nodesPath = getNodesPath(clustername);
createDirectoryStructureRecursive(nodesPath);
}
/**
* Get the path of the zookeeper clustername
* @param clustername
* @return
*/
protected String getClusterPath() {
return "/" + clustername;
}
/**
* Get the path of the zookeeper nodes
* @param clustername
* @return
*/
protected String getNodesPath(final String clustername) {
return getClusterPath() + "/nodes";
}
/**
* Get the path for the distribution group id queue
* @param distributionGroup
* @return
*/
protected String getDistributionGroupIdQueuePath(final String distributionGroup) {
return getDistributionGroupPath(distributionGroup) + "/" + NAME_PREFIXQUEUE;
}
/**
* Get the path for the distribution group
* @param distributionGroup
* @return
*/
protected String getDistributionGroupPath(final String distributionGroup) {
return getClusterPath() + "/" + distributionGroup;
}
@Override
public String getServicename() {
return "Zookeeper Client";
}
/**
* Create the given directory structure recursive
* @param path
* @throws ZookeeperException
*/
protected void createDirectoryStructureRecursive(final String path) throws ZookeeperException {
try {
// Does the full path already exists?
if(zookeeper.exists(path, this) != null) {
return;
}
// Otherwise check and create all sub paths
final String[] allNodes = path.split("/");
final StringBuilder sb = new StringBuilder();
// Start by 1 to skip the initial /
for (int i = 1; i < allNodes.length; i++) {
final String nextNode = allNodes[i];
sb.append("/");
sb.append(nextNode);
final String partialPath = sb.toString();
if(zookeeper.exists(partialPath, this) == null) {
logger.info(partialPath + " not found, creating");
zookeeper.create(partialPath,
"".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
}
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Get the next table id for a given distribution group
* @return
* @throws ZookeeperException
*/
public int getNextTableIdForDistributionGroup(final String distributionGroup) throws ZookeeperException {
final String distributionGroupIdQueuePath = getDistributionGroupIdQueuePath(distributionGroup);
createDirectoryStructureRecursive(distributionGroupIdQueuePath);
try {
final String nodename = zookeeper.create(distributionGroupIdQueuePath + "/" + SEQUENCE_QUEUE_PREFIX,
"".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT_SEQUENTIAL);
// Garbage collect the old child nodes
doIdQueueGarbageCollection(distributionGroupIdQueuePath);
// id-0000000063
// Element 0: id-
// Element 1: The number of the node
final String[] splittedName = nodename.split(SEQUENCE_QUEUE_PREFIX);
try {
return Integer.parseInt(splittedName[1]);
} catch(NumberFormatException e) {
logger.warn("Unable to parse number: " + splittedName[1], e);
throw new ZookeeperException(e);
}
} catch(InterruptedException | KeeperException e) {
throw new ZookeeperException(e);
}
}
/**
* Delete the old and unused child nodes for a given ID queue
* @param distributionGroupIdQueuePath
* @throws KeeperException
* @throws InterruptedException
*/
protected void doIdQueueGarbageCollection(final String distributionGroupIdQueuePath) throws KeeperException, InterruptedException {
final Random random = new Random(System.currentTimeMillis());
// 10 % garbage collection calls, 90% nop method calls
if((random.nextInt() % 100) > 90) {
logger.debug("Executing garbage collection on path: " + distributionGroupIdQueuePath);
final List<String> childs = zookeeper.getChildren(distributionGroupIdQueuePath, false);
for (Iterator<String> iterator = childs.iterator(); iterator.hasNext();) {
final String nodeName = iterator.next();
zookeeper.delete(distributionGroupIdQueuePath + "/" + nodeName, -1);
}
}
}
/**
* Read the structure of a distribution group
* @return
* @throws ZookeeperException
*/
public DistributionRegion readDistributionGroup(final String distributionGroup) throws ZookeeperException {
try {
final DistributionRegion root = DistributionRegion.createRootRegion(distributionGroup);
final String path = getDistributionGroupPath(distributionGroup);
readDistributionGroupRecursive(path, root);
return root;
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Read the distribution group in a recursive way
* @param path
* @param child
* @throws InterruptedException
* @throws KeeperException
*/
protected void readDistributionGroupRecursive(final String path, final DistributionRegion child) throws KeeperException, InterruptedException {
final String splitPathName = path + "/" + NAME_SPLIT;
if(zookeeper.exists(splitPathName, this) == null) {
return;
}
final byte[] bytes = zookeeper.getData(splitPathName, false, null);
final float splitFloat = Float.parseFloat(new String(bytes));
child.setSplit(splitFloat);
readDistributionGroupRecursive(path + "/" + NODE_LEFT, child.getLeftChild());
readDistributionGroupRecursive(path + "/" + NODE_RIGHT, child.getRightChild());
}
/**
* Delete the node recursive
* @param path
* @throws KeeperException
* @throws InterruptedException
*/
protected void deleteNodesRecursive(final String path) throws InterruptedException, KeeperException {
final List<String> childs = zookeeper.getChildren(path, false);
for(final String child: childs) {
deleteNodesRecursive(path + "/"+ child);
}
zookeeper.delete(path, -1);
}
/**
* Create a new distribution group
* @param distributionGroup
* @param replicationFactor
* @throws ZookeeperException
*/
public void createDistributionGroup(final String distributionGroup, final short replicationFactor) throws ZookeeperException {
try {
final String path = getDistributionGroupPath(distributionGroup);
zookeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
final int nameprefix = getNextTableIdForDistributionGroup(distributionGroup);
zookeeper.create(path + "/" + NAME_NAMEPREFIX, Integer.toString(nameprefix).getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zookeeper.create(path + "/" + NAME_REPLICATION, Short.toString(replicationFactor).getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Delete an existing distribution group
* @param distributionGroup
* @throws ZookeeperException
*/
public void deleteDistributionGroup(final String distributionGroup) throws ZookeeperException {
try {
final String path = getDistributionGroupPath(distributionGroup);
// Does the path not exist? We are done!
if(zookeeper.exists(path, this) == null) {
return;
}
deleteNodesRecursive(path);
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* List all existing distribution groups
* @return
* @throws ZookeeperException
*/
public List<DistributionGroupName> getDistributionGroups() throws ZookeeperException {
try {
final List<DistributionGroupName> groups = new ArrayList<DistributionGroupName>();
final String clusterPath = getClusterPath();
final List<String> nodes = zookeeper.getChildren(clusterPath, false);
for(final String node : nodes) {
final DistributionGroupName groupName = new DistributionGroupName(node);
if(groupName.isValid()) {
groups.add(groupName);
} else {
logger.warn("Got invalid distribution group name from zookeeper: " + groupName);
}
}
return groups;
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Get the replication factor for a distribution group
* @param distributionGroup
* @return
* @throws ZookeeperException
*/
public short getReplicationFactorForDistributionGroup(final String distributionGroup) throws ZookeeperException {
try {
final String path = getDistributionGroupPath(distributionGroup);
final String fullPath = path + "/" + NAME_REPLICATION;
final byte[] data = zookeeper.getData(fullPath, false, null);
try {
return Short.parseShort(new String(data));
} catch (NumberFormatException e) {
throw new ZookeeperException("Unable to parse replication factor: " + data + " for " + fullPath);
}
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Update zookeeper after splitting an region
* @param distributionRegion
* @throws ZookeeperException
*/
public void updateSplit(final DistributionRegion distributionRegion) throws ZookeeperException {
try {
final String zookeeperPath = getZookeeperPathForDistributionRegion(distributionRegion);
zookeeper.create(zookeeperPath + "/" + NAME_SPLIT, "".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
// Left child
final String leftPath = zookeeperPath + "/" + NODE_LEFT;
zookeeper.create(leftPath, "".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
final int leftNamePrefix = getNextTableIdForDistributionGroup(distributionRegion.getName());
zookeeper.create(leftPath + "/" + NAME_NAMEPREFIX, Integer.toString(leftNamePrefix).getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// Right child
final String rightPath = zookeeperPath + "/" + NODE_RIGHT;
zookeeper.create(rightPath, "".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
final int rightNamePrefix = getNextTableIdForDistributionGroup(distributionRegion.getName());
zookeeper.create(rightPath + "/" + NAME_NAMEPREFIX, Integer.toString(rightNamePrefix).getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException | InterruptedException e) {
throw new ZookeeperException(e);
}
}
/**
* Get the zookeeper path for a distribution region
* @param distributionRegion
* @return
*/
protected String getZookeeperPathForDistributionRegion(final DistributionRegion distributionRegion) {
final String name = distributionRegion.getName();
final StringBuilder sb = new StringBuilder();
DistributionRegion tmpRegion = distributionRegion;
while(tmpRegion.getRootRegion() != null) {
if(tmpRegion.isLeftChild()) {
sb.insert(0, "/" + NODE_LEFT);
} else {
sb.insert(0, "/" + NODE_RIGHT);
}
tmpRegion = tmpRegion.getRootRegion();
}
sb.insert(0, getDistributionGroupPath(name));
return sb.toString();
}
}
| Fixed node type | src/main/java/de/fernunihagen/dna/jkn/scalephant/distribution/ZookeeperClient.java | Fixed node type |
|
Java | apache-2.0 | 778d1f86706cc851ab0fe6492bfa8c104ec3b702 | 0 | asonipsl/hive,asonipsl/hive,WANdisco/amplab-hive,winningsix/hive,WANdisco/hive,winningsix/hive,wisgood/hive,winningsix/hive,WANdisco/hive,asonipsl/hive,asonipsl/hive,winningsix/hive,WANdisco/amplab-hive,wisgood/hive,wisgood/hive,asonipsl/hive,WANdisco/hive,WANdisco/amplab-hive,WANdisco/amplab-hive,WANdisco/hive,WANdisco/amplab-hive,winningsix/hive,wisgood/hive,WANdisco/hive,winningsix/hive,winningsix/hive,WANdisco/amplab-hive,wisgood/hive,asonipsl/hive,wisgood/hive,wisgood/hive,asonipsl/hive,winningsix/hive,asonipsl/hive,wisgood/hive,WANdisco/amplab-hive,WANdisco/amplab-hive,WANdisco/hive,WANdisco/hive,WANdisco/hive | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.io.parquet.serde;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.apache.hadoop.hive.ql.io.parquet.timestamp.NanoTime;
import org.apache.hadoop.hive.ql.io.parquet.timestamp.NanoTimeUtils;
/**
* Tests util-libraries used for parquet-timestamp.
*/
public class TestParquetTimestampUtils extends TestCase {
public void testJulianDay() {
//check if May 23, 1968 is Julian Day 2440000
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1968);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 23);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts = new Timestamp(cal.getTimeInMillis());
NanoTime nt = NanoTimeUtils.getNanoTime(ts);
Assert.assertEquals(nt.getJulianDay(), 2440000);
Timestamp tsFetched = NanoTimeUtils.getTimestamp(nt);
Assert.assertEquals(tsFetched, ts);
//check if 30 Julian Days between Jan 1, 2005 and Jan 31, 2005.
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.YEAR, 2005);
cal1.set(Calendar.MONTH, Calendar.JANUARY);
cal1.set(Calendar.DAY_OF_MONTH, 1);
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts1 = new Timestamp(cal1.getTimeInMillis());
NanoTime nt1 = NanoTimeUtils.getNanoTime(ts1);
Timestamp ts1Fetched = NanoTimeUtils.getTimestamp(nt1);
Assert.assertEquals(ts1Fetched, ts1);
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.YEAR, 2005);
cal2.set(Calendar.MONTH, Calendar.JANUARY);
cal2.set(Calendar.DAY_OF_MONTH, 31);
cal2.set(Calendar.HOUR_OF_DAY, 0);
cal2.setTimeZone(TimeZone.getTimeZone("UTC"));
Timestamp ts2 = new Timestamp(cal2.getTimeInMillis());
NanoTime nt2 = NanoTimeUtils.getNanoTime(ts2);
Timestamp ts2Fetched = NanoTimeUtils.getTimestamp(nt2);
Assert.assertEquals(ts2Fetched, ts2);
Assert.assertEquals(nt2.getJulianDay() - nt1.getJulianDay(), 30);
}
public void testNanos() {
//case 1: 01:01:01.0000000001
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1968);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 23);
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 1);
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts = new Timestamp(cal.getTimeInMillis());
ts.setNanos(1);
//(1*60*60 + 1*60 + 1) * 10e9 + 1
NanoTime nt = NanoTimeUtils.getNanoTime(ts);
Assert.assertEquals(nt.getTimeOfDayNanos(), 3661000000001L);
//case 2: 23:59:59.999999999
cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1968);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 23);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
ts = new Timestamp(cal.getTimeInMillis());
ts.setNanos(999999999);
//(23*60*60 + 59*60 + 59)*10e9 + 999999999
nt = NanoTimeUtils.getNanoTime(ts);
Assert.assertEquals(nt.getTimeOfDayNanos(), 86399999999999L);
//case 3: verify the difference.
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.YEAR, 1968);
cal2.set(Calendar.MONTH, Calendar.MAY);
cal2.set(Calendar.DAY_OF_MONTH, 23);
cal2.set(Calendar.HOUR_OF_DAY, 0);
cal2.set(Calendar.MINUTE, 10);
cal2.set(Calendar.SECOND, 0);
cal2.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts2 = new Timestamp(cal2.getTimeInMillis());
ts2.setNanos(10);
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.YEAR, 1968);
cal1.set(Calendar.MONTH, Calendar.MAY);
cal1.set(Calendar.DAY_OF_MONTH, 23);
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
cal1.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts1 = new Timestamp(cal1.getTimeInMillis());
ts1.setNanos(1);
NanoTime n2 = NanoTimeUtils.getNanoTime(ts2);
NanoTime n1 = NanoTimeUtils.getNanoTime(ts1);
Assert.assertEquals(n2.getTimeOfDayNanos() - n1.getTimeOfDayNanos(), 600000000009L);
}
public void testTimezone() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1968);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 23);
cal.set(Calendar.HOUR_OF_DAY, 17);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 1);
cal.setTimeZone(TimeZone.getTimeZone("US/Pacific"));
Timestamp ts = new Timestamp(cal.getTimeInMillis());
ts.setNanos(1);
/**
* 17:00 PDT = 00:00 GMT (daylight-savings)
* (0*60*60 + 1*60 + 1)*10e9 + 1 = 61000000001, or
*
* 17:00 PST = 01:00 GMT (if not daylight savings)
* (1*60*60 + 1*60 + 1)*10e9 + 1 = 3661000000001
*/
NanoTime nt = NanoTimeUtils.getNanoTime(ts);
long timeOfDayNanos = nt.getTimeOfDayNanos();
Assert.assertTrue(timeOfDayNanos == 61000000001L || timeOfDayNanos == 3661000000001L);
//in both cases, this will be the next day in GMT
Assert.assertEquals(nt.getJulianDay(), 2440001);
}
public void testValues() {
//exercise a broad range of timestamps close to the present.
verifyTsString("2011-01-01 01:01:01.111111111");
verifyTsString("2012-02-02 02:02:02.222222222");
verifyTsString("2013-03-03 03:03:03.333333333");
verifyTsString("2014-04-04 04:04:04.444444444");
verifyTsString("2015-05-05 05:05:05.555555555");
verifyTsString("2016-06-06 06:06:06.666666666");
verifyTsString("2017-07-07 07:07:07.777777777");
verifyTsString("2018-08-08 08:08:08.888888888");
verifyTsString("2019-09-09 09:09:09.999999999");
verifyTsString("2020-10-10 10:10:10.101010101");
verifyTsString("2021-11-11 11:11:11.111111111");
verifyTsString("2022-12-12 12:12:12.121212121");
verifyTsString("2023-01-02 13:13:13.131313131");
verifyTsString("2024-02-02 14:14:14.141414141");
verifyTsString("2025-03-03 15:15:15.151515151");
verifyTsString("2026-04-04 16:16:16.161616161");
verifyTsString("2027-05-05 17:17:17.171717171");
verifyTsString("2028-06-06 18:18:18.181818181");
verifyTsString("2029-07-07 19:19:19.191919191");
verifyTsString("2030-08-08 20:20:20.202020202");
verifyTsString("2031-09-09 21:21:21.212121212");
//test some extreme cases.
verifyTsString("9999-09-09 09:09:09.999999999");
verifyTsString("0001-01-01 00:00:00.0");
}
private void verifyTsString(String tsString) {
Timestamp ts = Timestamp.valueOf(tsString);
NanoTime nt = NanoTimeUtils.getNanoTime(ts);
Timestamp tsFetched = NanoTimeUtils.getTimestamp(nt);
Assert.assertEquals(tsString, tsFetched.toString());
}
}
| ql/src/test/org/apache/hadoop/hive/ql/io/parquet/serde/TestParquetTimestampUtils.java | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.io.parquet.serde;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.apache.hadoop.hive.ql.io.parquet.timestamp.NanoTime;
import org.apache.hadoop.hive.ql.io.parquet.timestamp.NanoTimeUtils;
/**
* Tests util-libraries used for parquet-timestamp.
*/
public class TestParquetTimestampUtils extends TestCase {
public void testJulianDay() {
//check if May 23, 1968 is Julian Day 2440000
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1968);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 23);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts = new Timestamp(cal.getTimeInMillis());
NanoTime nt = NanoTimeUtils.getNanoTime(ts);
Assert.assertEquals(nt.getJulianDay(), 2440000);
Timestamp tsFetched = NanoTimeUtils.getTimestamp(nt);
Assert.assertEquals(tsFetched, ts);
//check if 30 Julian Days between Jan 1, 2005 and Jan 31, 2005.
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.YEAR, 2005);
cal1.set(Calendar.MONTH, Calendar.JANUARY);
cal1.set(Calendar.DAY_OF_MONTH, 1);
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts1 = new Timestamp(cal1.getTimeInMillis());
NanoTime nt1 = NanoTimeUtils.getNanoTime(ts1);
Timestamp ts1Fetched = NanoTimeUtils.getTimestamp(nt1);
Assert.assertEquals(ts1Fetched, ts1);
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.YEAR, 2005);
cal2.set(Calendar.MONTH, Calendar.JANUARY);
cal2.set(Calendar.DAY_OF_MONTH, 31);
cal2.set(Calendar.HOUR_OF_DAY, 0);
cal2.setTimeZone(TimeZone.getTimeZone("UTC"));
Timestamp ts2 = new Timestamp(cal2.getTimeInMillis());
NanoTime nt2 = NanoTimeUtils.getNanoTime(ts2);
Timestamp ts2Fetched = NanoTimeUtils.getTimestamp(nt2);
Assert.assertEquals(ts2Fetched, ts2);
Assert.assertEquals(nt2.getJulianDay() - nt1.getJulianDay(), 30);
}
public void testNanos() {
//case 1: 01:01:01.0000000001
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1968);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 23);
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 1);
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts = new Timestamp(cal.getTimeInMillis());
ts.setNanos(1);
//(1*60*60 + 1*60 + 1) * 10e9 + 1
NanoTime nt = NanoTimeUtils.getNanoTime(ts);
Assert.assertEquals(nt.getTimeOfDayNanos(), 3661000000001L);
//case 2: 23:59:59.999999999
cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1968);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 23);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
ts = new Timestamp(cal.getTimeInMillis());
ts.setNanos(999999999);
//(23*60*60 + 59*60 + 59)*10e9 + 999999999
nt = NanoTimeUtils.getNanoTime(ts);
Assert.assertEquals(nt.getTimeOfDayNanos(), 86399999999999L);
//case 3: verify the difference.
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.YEAR, 1968);
cal2.set(Calendar.MONTH, Calendar.MAY);
cal2.set(Calendar.DAY_OF_MONTH, 23);
cal2.set(Calendar.HOUR_OF_DAY, 0);
cal2.set(Calendar.MINUTE, 10);
cal2.set(Calendar.SECOND, 0);
cal2.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts2 = new Timestamp(cal2.getTimeInMillis());
ts2.setNanos(10);
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.YEAR, 1968);
cal1.set(Calendar.MONTH, Calendar.MAY);
cal1.set(Calendar.DAY_OF_MONTH, 23);
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
cal1.setTimeZone(TimeZone.getTimeZone("GMT"));
Timestamp ts1 = new Timestamp(cal1.getTimeInMillis());
ts1.setNanos(1);
NanoTime n2 = NanoTimeUtils.getNanoTime(ts2);
NanoTime n1 = NanoTimeUtils.getNanoTime(ts1);
Assert.assertEquals(n2.getTimeOfDayNanos() - n1.getTimeOfDayNanos(), 600000000009L);
}
public void testTimezone() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1968);
cal.set(Calendar.MONTH, Calendar.MAY);
cal.set(Calendar.DAY_OF_MONTH, 23);
if ((TimeZone.getTimeZone("US/Pacific").inDaylightTime(new Date()))) {
cal.set(Calendar.HOUR_OF_DAY, 18);
} else {
cal.set(Calendar.HOUR_OF_DAY, 17);
}
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 1);
cal.setTimeZone(TimeZone.getTimeZone("US/Pacific"));
Timestamp ts = new Timestamp(cal.getTimeInMillis());
ts.setNanos(1);
//18:00 PST = 01:00 GMT (if daylight-savings)
//17:00 PST = 01:00 GMT (if not daylight savings)
//(1*60*60 + 1*60 + 1)*10e9 + 1
NanoTime nt = NanoTimeUtils.getNanoTime(ts);
Assert.assertEquals(nt.getTimeOfDayNanos(), 3661000000001L);
//in both cases, this will be the next day in GMT
Assert.assertEquals(nt.getJulianDay(), 2440001);
}
public void testValues() {
//exercise a broad range of timestamps close to the present.
verifyTsString("2011-01-01 01:01:01.111111111");
verifyTsString("2012-02-02 02:02:02.222222222");
verifyTsString("2013-03-03 03:03:03.333333333");
verifyTsString("2014-04-04 04:04:04.444444444");
verifyTsString("2015-05-05 05:05:05.555555555");
verifyTsString("2016-06-06 06:06:06.666666666");
verifyTsString("2017-07-07 07:07:07.777777777");
verifyTsString("2018-08-08 08:08:08.888888888");
verifyTsString("2019-09-09 09:09:09.999999999");
verifyTsString("2020-10-10 10:10:10.101010101");
verifyTsString("2021-11-11 11:11:11.111111111");
verifyTsString("2022-12-12 12:12:12.121212121");
verifyTsString("2023-01-02 13:13:13.131313131");
verifyTsString("2024-02-02 14:14:14.141414141");
verifyTsString("2025-03-03 15:15:15.151515151");
verifyTsString("2026-04-04 16:16:16.161616161");
verifyTsString("2027-05-05 17:17:17.171717171");
verifyTsString("2028-06-06 18:18:18.181818181");
verifyTsString("2029-07-07 19:19:19.191919191");
verifyTsString("2030-08-08 20:20:20.202020202");
verifyTsString("2031-09-09 21:21:21.212121212");
//test some extreme cases.
verifyTsString("9999-09-09 09:09:09.999999999");
verifyTsString("0001-01-01 00:00:00.0");
}
private void verifyTsString(String tsString) {
Timestamp ts = Timestamp.valueOf(tsString);
NanoTime nt = NanoTimeUtils.getNanoTime(ts);
Timestamp tsFetched = NanoTimeUtils.getTimestamp(nt);
Assert.assertEquals(tsString, tsFetched.toString());
}
}
| HIVE-8713 : Unit test TestParquetTimestampUtils.testTimezone failing (Szehon, reviewed by Brock)
git-svn-id: c2303eb81cb646bce052f55f7f0d14f181a5956c@1636484 13f79535-47bb-0310-9956-ffa450edef68
| ql/src/test/org/apache/hadoop/hive/ql/io/parquet/serde/TestParquetTimestampUtils.java | HIVE-8713 : Unit test TestParquetTimestampUtils.testTimezone failing (Szehon, reviewed by Brock) |
|
Java | apache-2.0 | 1f8aab9cc03ef3df85eed53d9c8fd35bd17394c6 | 0 | groybal/uPortal,groybal/uPortal,groybal/uPortal,GIP-RECIA/esup-uportal,bjagg/uPortal,Jasig/uPortal,cousquer/uPortal,bjagg/uPortal,jonathanmtran/uPortal,GIP-RECIA/esco-portail,GIP-RECIA/esco-portail,GIP-RECIA/esup-uportal,cousquer/uPortal,jonathanmtran/uPortal,mgillian/uPortal,ChristianMurphy/uPortal,cousquer/uPortal,Jasig/uPortal,ChristianMurphy/uPortal,GIP-RECIA/esup-uportal,GIP-RECIA/esup-uportal,bjagg/uPortal,jonathanmtran/uPortal,GIP-RECIA/esco-portail,GIP-RECIA/esup-uportal,Jasig/uPortal,ChristianMurphy/uPortal,mgillian/uPortal,groybal/uPortal,groybal/uPortal,mgillian/uPortal | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apereo.portal.layout.dlm;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apereo.portal.EntityIdentifier;
import org.apereo.portal.portlet.om.IPortletDefinition;
import org.apereo.portal.portlet.om.IPortletDefinitionId;
import org.apereo.portal.portlet.om.IPortletDefinitionParameter;
import org.apereo.portal.portlet.om.IPortletDescriptorKey;
import org.apereo.portal.portlet.om.IPortletLifecycleEntry;
import org.apereo.portal.portlet.om.IPortletPreference;
import org.apereo.portal.portlet.om.IPortletType;
import org.apereo.portal.portlet.om.PortletLifecycleState;
import org.apereo.portal.security.IPerson;
/**
* {@link IPortletDefinition} implementation representing a missing portlet, meaning a portlet that
* could not be found, or a portlet that is not approved.
*/
public class MissingPortletDefinition implements IPortletDefinition {
private static final String FNAME = "DLMStaticMissingChannel";
/* package-private */ static final String CHANNEL_ID = "-1";
public static final IPortletDefinition INSTANCE = new MissingPortletDefinition();
private MissingPortletDefinition() {
// prevent instantiation outside of this class
}
@Override
public String getName() {
return "Missing channel";
}
@Override
public String getName(String locale) {
return "Missing channel";
}
@Override
public int getTimeout() {
return 20000;
}
@Override
public String getTitle() {
return "Missing channel";
}
@Override
public String getTitle(String locale) {
return "Missing channel";
}
@Override
public String getAlternativeMaximizedLink() {
return null;
}
@Override
public String getTarget() {
return null;
}
@Override
public String getFName() {
return FNAME;
}
@Override
public String getDataId() {
return null;
}
@Override
public String getDataTitle() {
return this.getName();
}
@Override
public String getDataDescription() {
return this.getDescription();
}
@Override
public Integer getActionTimeout() {
return null;
}
@Override
public Integer getEventTimeout() {
return null;
}
@Override
public Integer getRenderTimeout() {
return null;
}
@Override
public Integer getResourceTimeout() {
return null;
}
@Override
public void setActionTimeout(Integer actionTimeout) {}
@Override
public void setEventTimeout(Integer eventTimeout) {}
@Override
public void setRenderTimeout(Integer renderTimeout) {}
@Override
public void setResourceTimeout(Integer resourceTimeout) {}
@Override
public Double getRating() {
return null;
}
@Override
public void setRating(Double rating) {}
@Override
public Long getUsersRated() {
return null;
}
@Override
public void setUsersRated(Long usersRated) {}
@Override
public void addLocalizedDescription(String locale, String chanDesc) {}
@Override
public void addLocalizedName(String locale, String chanName) {}
@Override
public void addLocalizedTitle(String locale, String chanTitle) {}
@Override
public void addParameter(IPortletDefinitionParameter parameter) {}
@Override
public String getDescription() {
return null;
}
@Override
public String getDescription(String locale) {
return null;
}
@Override
public EntityIdentifier getEntityIdentifier() {
return null;
}
@Override
public IPortletDefinitionParameter getParameter(String key) {
return null;
}
@Override
public Set<IPortletDefinitionParameter> getParameters() {
return Collections.emptySet();
}
@Override
public Map<String, IPortletDefinitionParameter> getParametersAsUnmodifiableMap() {
return Collections.emptyMap();
}
@Override
public void removeParameter(IPortletDefinitionParameter parameter) {}
@Override
public void removeParameter(String name) {}
@Override
public void setDescription(String descr) {}
@Override
public void setFName(String fname) {}
@Override
public void setName(String name) {}
@Override
public void setParameters(Set<IPortletDefinitionParameter> parameters) {}
@Override
public void setTimeout(int timeout) {}
@Override
public void setTitle(String title) {}
@Override
public IPortletType getType() {
return new MissingPortletType();
}
public void setType(IPortletType channelType) {}
@Override
public PortletLifecycleState getLifecycleState() {
return null;
}
@Override
public void updateLifecycleState(PortletLifecycleState lifecycleState, IPerson user) {}
@Override
public void updateLifecycleState(
PortletLifecycleState lifecycleState, IPerson user, Date timestamp) {}
@Override
public List<IPortletLifecycleEntry> getLifecycle() {
return null;
}
@Override
public void clearLifecycle() {}
@Override
public IPortletDefinitionId getPortletDefinitionId() {
return new MissingPortletDefinitionId();
}
@Override
public List<IPortletPreference> getPortletPreferences() {
return Collections.emptyList();
}
@Override
public void addParameter(String name, String value) {}
@Override
public boolean setPortletPreferences(List<IPortletPreference> portletPreferences) {
return false;
}
@Override
public IPortletDescriptorKey getPortletDescriptorKey() {
return null;
}
@Override
public String toString() {
return "MissingPortletDefinition [fname=" + FNAME + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + FNAME.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
// there is only one instance, so this should suffice
return this == obj;
}
private static final class MissingPortletDefinitionId implements IPortletDefinitionId {
private static final long serialVersionUID = 1L;
private final long id = -1;
private final String strId = Long.toString(id);
@Override
public String getStringId() {
return strId;
}
@Override
public long getLongId() {
return id;
}
}
private static final class MissingPortletType implements IPortletType {
@Override
public int getId() {
return -1;
}
@Override
public String getName() {
return null;
}
@Override
public String getDescription() {
return null;
}
@Override
public String getCpdUri() {
return null;
}
@Override
public void setDescription(String descr) {}
@Override
public void setCpdUri(String cpdUri) {}
@Override
public String getDataId() {
return null;
}
@Override
public String getDataTitle() {
return null;
}
@Override
public String getDataDescription() {
return null;
}
}
}
| uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/MissingPortletDefinition.java | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apereo.portal.layout.dlm;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apereo.portal.EntityIdentifier;
import org.apereo.portal.portlet.om.IPortletDefinition;
import org.apereo.portal.portlet.om.IPortletDefinitionId;
import org.apereo.portal.portlet.om.IPortletDefinitionParameter;
import org.apereo.portal.portlet.om.IPortletDescriptorKey;
import org.apereo.portal.portlet.om.IPortletLifecycleEntry;
import org.apereo.portal.portlet.om.IPortletPreference;
import org.apereo.portal.portlet.om.IPortletType;
import org.apereo.portal.portlet.om.PortletLifecycleState;
import org.apereo.portal.security.IPerson;
/**
* {@link IPortletDefinition} implementation representing a missing portlet, meaning a portlet that
* could not be found, or a portlet that is not approved.
*/
public class MissingPortletDefinition implements IPortletDefinition {
private static final String FNAME = "DLMStaticMissingChannel";
/* package-private */ static final String CHANNEL_ID = "-1";
public static final IPortletDefinition INSTANCE = new MissingPortletDefinition();
private MissingPortletDefinition() {
// prevent instantiation outside of this class
}
@Override
public String getName() {
return "Missing channel";
}
@Override
public String getName(String locale) {
return "Missing channel";
}
@Override
public int getTimeout() {
return 20000;
}
@Override
public String getTitle() {
return "Missing channel";
}
@Override
public String getTitle(String locale) {
return "Missing channel";
}
@Override
public String getAlternativeMaximizedLink() {
return null;
}
@Override
public String getTarget() {
return null;
}
@Override
public String getFName() {
return FNAME;
}
@Override
public String getDataId() {
return null;
}
@Override
public String getDataTitle() {
return this.getName();
}
@Override
public String getDataDescription() {
return this.getDescription();
}
@Override
public Integer getActionTimeout() {
return null;
}
@Override
public Integer getEventTimeout() {
return null;
}
@Override
public Integer getRenderTimeout() {
return null;
}
@Override
public Integer getResourceTimeout() {
return null;
}
@Override
public void setActionTimeout(Integer actionTimeout) {}
@Override
public void setEventTimeout(Integer eventTimeout) {}
@Override
public void setRenderTimeout(Integer renderTimeout) {}
@Override
public void setResourceTimeout(Integer resourceTimeout) {}
@Override
public Double getRating() {
return null;
}
@Override
public void setRating(Double rating) {}
@Override
public Long getUsersRated() {
return null;
}
@Override
public void setUsersRated(Long usersRated) {}
@Override
public void addLocalizedDescription(String locale, String chanDesc) {}
@Override
public void addLocalizedName(String locale, String chanName) {}
@Override
public void addLocalizedTitle(String locale, String chanTitle) {}
@Override
public void addParameter(IPortletDefinitionParameter parameter) {}
@Override
public String getDescription() {
return null;
}
@Override
public String getDescription(String locale) {
return null;
}
@Override
public EntityIdentifier getEntityIdentifier() {
return null;
}
@Override
public IPortletDefinitionParameter getParameter(String key) {
return null;
}
@Override
public Set<IPortletDefinitionParameter> getParameters() {
return Collections.emptySet();
}
@Override
public Map<String, IPortletDefinitionParameter> getParametersAsUnmodifiableMap() {
return Collections.emptyMap();
}
@Override
public void removeParameter(IPortletDefinitionParameter parameter) {}
@Override
public void removeParameter(String name) {}
@Override
public void setDescription(String descr) {}
@Override
public void setFName(String fname) {}
@Override
public void setName(String name) {}
@Override
public void setParameters(Set<IPortletDefinitionParameter> parameters) {}
@Override
public void setTimeout(int timeout) {}
@Override
public void setTitle(String title) {}
@Override
public IPortletType getType() {
return new MissingPortletType();
}
public void setType(IPortletType channelType) {}
@Override
public PortletLifecycleState getLifecycleState() {
return null;
}
@Override
public void updateLifecycleState(PortletLifecycleState lifecycleState, IPerson user) {}
@Override
public void updateLifecycleState(
PortletLifecycleState lifecycleState, IPerson user, Date timestamp) {}
@Override
public List<IPortletLifecycleEntry> getLifecycle() {
return null;
}
@Override
public void clearLifecycle() {}
@Override
public IPortletDefinitionId getPortletDefinitionId() {
return new MissingPortletDefinitionId();
}
@Override
public List<IPortletPreference> getPortletPreferences() {
return Collections.emptyList();
}
@Override
public void addParameter(String name, String value) {}
@Override
public boolean setPortletPreferences(List<IPortletPreference> portletPreferences) {
return false;
}
@Override
public IPortletDescriptorKey getPortletDescriptorKey() {
return null;
}
@Override
public String toString() {
return "MissingPortletDefinition [fname=" + FNAME + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + FNAME.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
// there is only one instance, so this should suffice
return this == obj;
}
private static final class MissingPortletDefinitionId implements IPortletDefinitionId {
private static final long serialVersionUID = 1L;
private final long id = -1;
private final String strId = Long.toString(id);
@Override
public String getStringId() {
return strId;
}
@Override
public long getLongId() {
return id;
}
}
private static final class MissingPortletType implements IPortletType {
@Override
public int getId() {
return -1;
}
@Override
public String getName() {
return null;
}
@Override
public String getDescription() {
return null;
}
@Override
public String getCpdUri() {
return null;
}
public void setDescription(String descr) {}
@Override
public void setCpdUri(String cpdUri) {}
@Override
public String getDataId() {
return null;
}
@Override
public String getDataTitle() {
return null;
}
@Override
public String getDataDescription() {
return null;
}
}
}
| docs: annotate .MissingPortletType setDescription() as @Override
Addresses
/uPortal/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/MissingPortletDefinition.java:323: warning: [MissingOverride] setDescription implements method in IPortletType; expected @Override
public void setDescription(String descr) {}
^
(see http://errorprone.info/bugpattern/MissingOverride) | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/MissingPortletDefinition.java | docs: annotate .MissingPortletType setDescription() as @Override |
|
Java | apache-2.0 | ec5e1baf01f68e1f87930794d64e4d8c21aee081 | 0 | sensor-cesca/sensor-cesca,sensor-cesca/sensor-cesca,sensor-cesca/sensor-cesca,sensor-cesca/sensor-cesca | package com.cesca.sensors.service;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import com.cesca.sensors.entity.DHTSensor;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
@Controller
public class DHTSensorSerialMonitorService implements SerialPortEventListener {
@Autowired
public DHTSensorService dhtSensorService;
private SerialPort serialPort;
private String output = "";
private Logger log = Logger.getLogger(this.getClass());
public DHTSensorSerialMonitorService(@Value("${app.dhtsensor.reader.portName}") String portName) {
this.serialPort = new SerialPort(portName);
boolean connected = false;
while (!connected){
try {
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);// Set params.
serialPort.addEventListener(this);// Add
connected = true;
} catch (SerialPortException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
@Override
public void serialEvent(SerialPortEvent event) {
log.debug("Event received");
if (event.isRXCHAR()) {
try {
String serialOutput = this.serialPort.readString();
if (serialOutput != null){
serialOutput.replaceAll("null", "");
this.output += serialOutput;
String[] lines = output.split("\n\r");
String lineToBeProcessed = null;
for (String line : lines) {
String[] values = line.split(" ");
if ( (line.length() == 11) && (values.length == 2)) {
if (values[0].length() == values[1].length()) {
lineToBeProcessed = line;
}
}
}
if (lineToBeProcessed != null) {
this.processSerialLine(lineToBeProcessed);
}
}
} catch (SerialPortException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
} else {
log.debug("Event is not RXCHAR");
log.debug("Event : " + event.toString());
}
}
private void processSerialLine(String lineToBeProcessed) {
log.info("Processing: " + lineToBeProcessed);
String[] values = lineToBeProcessed.split(" ");
long collectedTimeStamp = System.currentTimeMillis();
float humidity = Float.parseFloat(values[0] + "f");
float temperature = Float.parseFloat(values[1] + "f");
if ( (humidity < 100) && (temperature < 100) ){
DHTSensor dht = new DHTSensor(collectedTimeStamp, humidity, temperature);
this.dhtSensorService.addDHTSensorData(dht);
}
this.output = "";
}
} | src/main/java/com/cesca/sensors/service/DHTSensorSerialMonitorService.java | package com.cesca.sensors.service;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import com.cesca.sensors.entity.DHTSensor;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
@Controller
public class DHTSensorSerialMonitorService implements SerialPortEventListener {
@Autowired
public DHTSensorService dhtSensorService;
private SerialPort serialPort;
private String output = "";
private Logger log = Logger.getLogger(this.getClass());
public DHTSensorSerialMonitorService(@Value("${app.dhtsensor.reader.portName}") String portName) {
this.serialPort = new SerialPort(portName);
try {
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);// Set params.
serialPort.addEventListener(this);// Add
} catch (SerialPortException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void serialEvent(SerialPortEvent event) {
log.debug("Event received");
if (event.isRXCHAR()) {
try {
String serialOutput = this.serialPort.readString();
serialOutput.replaceAll("null", "");
this.output += serialOutput;
String[] lines = output.split("\n\r");
String lineToBeProcessed = null;
for (String line : lines) {
String[] values = line.split(" ");
if ( (line.length() == 11) && (values.length == 2)) {
if (values[0].length() == values[1].length()) {
lineToBeProcessed = line;
}
}
}
if (lineToBeProcessed != null) {
this.processSerialLine(lineToBeProcessed);
}
} catch (SerialPortException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
} else {
log.debug("Event is not RXCHAR");
log.debug("Event : " + event.toString());
}
}
private void processSerialLine(String lineToBeProcessed) {
log.info("Processing: " + lineToBeProcessed);
String[] values = lineToBeProcessed.split(" ");
long collectedTimeStamp = System.currentTimeMillis();
float humidity = Float.parseFloat(values[0] + "f");
float temperature = Float.parseFloat(values[1] + "f");
if ( (humidity < 100) && (temperature < 100) ){
DHTSensor dht = new DHTSensor(collectedTimeStamp, humidity, temperature);
this.dhtSensorService.addDHTSensorData(dht);
}
this.output = "";
}
} | Add handler for null values
| src/main/java/com/cesca/sensors/service/DHTSensorSerialMonitorService.java | Add handler for null values |
|
Java | mit | 24e5f4c51ac16e920ebb0ecd6796cf8da9c19cd4 | 0 | skdkim/cj-learn | package test.com.cjpowered.learn.inventory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import com.cjpowered.learn.inventory.InventoryDatabase;
import com.cjpowered.learn.inventory.InventoryManager;
import com.cjpowered.learn.inventory.Item;
import com.cjpowered.learn.inventory.Order;
import com.cjpowered.learn.inventory.StockedItem;
import com.cjpowered.learn.inventory.ace.AceInventoryManager;
import com.cjpowered.learn.marketing.MarketingInfo;
import com.cjpowered.learn.marketing.Season;
/*
* We need to keep items in stock to prevent back orders. See the README.md
* for the requirements.
*
*/
public class InventoryTest {
@Test
public void doNotRefillStockWhenNoOrders() {
// given
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public List<Item> stockItems(){
return Collections.emptyList();
}
};
final LocalDate today = LocalDate.now();
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return null;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertTrue(actualOrders.isEmpty());
}
@Test
public void refillSingleStock(){
// given
int onHand = 10;
int shouldHave = 16;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(item, actualOrders.get(0).item);
assertEquals(shouldHave - onHand, actualOrders.get(0).quantity);
}
@Test
public void doNotRefillSingleStockSurplus(){
// given
int onHand = 16;
int shouldHave = 10;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return onHand;
}
@Override
public List<Item> stockItems(){
return Collections.singletonList(item);
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
assertTrue(actualOrders.isEmpty());
}
@Test
public void doNotRefillStockPerfectCount(){
// given
int onHand = 10;
int shouldHave = 10;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return onHand;
}
@Override
public List<Item> stockItems(){
return Collections.singletonList(item);
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
assertTrue(actualOrders.isEmpty());
}
@Test
public void refillMultipleStock(){
// given
int onHandA = 10;
int onHandB = 12;
int shouldHaveA = 16;
int shouldHaveB = 20;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
assertEquals(itemA, actualOrders.get(0).item);
assertEquals(itemB, actualOrders.get(1).item);
assertEquals(shouldHaveA - onHandA, actualOrders.get(0).quantity);
assertEquals(shouldHaveB - onHandB, actualOrders.get(1).quantity);
}
@Test
public void refillMultipleStockOneOnly(){
// given
int onHandA = 10;
int onHandB = 12;
int shouldHaveA = 8;
int shouldHaveB = 20;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(itemB, actualOrders.get(0).item);
assertEquals(shouldHaveB - onHandB, actualOrders.get(0).quantity);
}
@Test(expected=IndexOutOfBoundsException.class)
public void doNotRefillInvalidStockOnMultipleOrder(){
// given
int onHandA = 10;
int onHandB = 12;
int shouldHaveA = 8;
int shouldHaveB = 20;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
Item nonExistantItem = actualOrders.get(1).item;
}
@Test
public void refillSaleStock(){
// given
int onHand = 10;
int shouldHave = 15;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return onHand;
}
@Override
public List<Item> stockItems(){
return Collections.singletonList(item);
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(shouldHave - onHand + 20, actualOrders.get(0).quantity);
}
@Test
public void doNotRefillSaleStockPerfectCount(){
// given
int onHand = 35;
int shouldHave = 15;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return onHand;
}
@Override
public List<Item> stockItems(){
return Collections.singletonList(item);
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
}
@Test
public void refillMultipleSaleStock(){
// given
int onHandA = 34;
int onHandB = 34;
int shouldHaveA = 15;
int shouldHaveB = 15;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
assertEquals(itemA, actualOrders.get(0).item);
assertEquals(itemB, actualOrders.get(1).item);
assertEquals(shouldHaveA - onHandA + 20, actualOrders.get(0).quantity);
assertEquals(shouldHaveB - onHandB + 20, actualOrders.get(1).quantity);
}
@Test
public void refillMixStockSaleAndRegular(){
// given
int onHandA = 30;
int onHandB = 14;
int shouldHaveA = 15;
int shouldHaveB = 18;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return item == itemA ? true : false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
assertEquals(itemA, actualOrders.get(0).item);
assertEquals(itemB, actualOrders.get(1).item);
assertEquals(shouldHaveA - onHandA + 20, actualOrders.get(0).quantity);
assertEquals(shouldHaveB - onHandB, actualOrders.get(1).quantity);
}
@Test
public void refillSingleSeasonalStock(){
// given
int onHand = 10;
int shouldHave = 16;
final Season season = Season.Summer;
final boolean isRestricted = false;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(item, actualOrders.get(0).item);
assertEquals((shouldHave * 2) - onHand, actualOrders.get(0).quantity);
}
@Test
public void doNotRefillSingleSeasonalStock(){
// given
int onHand = 40;
int shouldHave = 20;
final Season season = Season.Summer;
final boolean isRestricted = false;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
}
@Test
public void refillMultipleSeasonalStock(){
// given
int onHandA = 39;
int shouldHaveA = 20;
int onHandB = 21;
int shouldHaveB = 15;
final Season season = Season.Summer;
final boolean isRestricted = false;
Item itemA = new SeasonalItem(shouldHaveA, season, isRestricted);
Item itemB = new SeasonalItem(shouldHaveB, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(itemA, onHandA);
store.put(itemB, onHandB);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
final Order expectedOrderA = new Order(itemA, (2 * 20) - 39);
final Order expectedOrderB = new Order(itemB, (2 * 15) - 21);
HashSet<Order> expected = new HashSet<>();
expected.add(expectedOrderA);
expected.add(expectedOrderB);
assertEquals(expected, new HashSet<>(actualOrders));
}
@Test
public void refillMixStockSeasonalAndRegular(){
// given
int onHandA = 39;
int shouldHaveA = 20;
int onHandB = 10;
int shouldHaveB = 15;
final Season seasonA = Season.Summer;
final Season seasonB = Season.Spring;
boolean isRestricted = false;
Item itemA = new SeasonalItem(shouldHaveA, seasonA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(itemA, onHandA);
store.put(itemB, onHandB);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
final Order expectedOrderA = new Order(itemA, (2 * 20) - 39);
final Order expectedOrderB = new Order(itemB, 15 - 10);
HashSet<Order> expected = new HashSet<>();
expected.add(expectedOrderA);
expected.add(expectedOrderB);
assertEquals(expected, new HashSet<>(actualOrders));
}
@Test
public void refillMixStockSeasonalAndSale(){
// given
int onHandA = 39;
int shouldHaveA = 20;
int onHandB = 10;
int shouldHaveB = 15;
final Season season = Season.Summer;
boolean isRestricted = false;
Item itemA = new SeasonalItem(shouldHaveA, season, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(itemA, onHandA);
store.put(itemB, onHandB);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return item == itemB ? true : false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
final Order expectedOrderA = new Order(itemA, (2 * 20) - 39);
final Order expectedOrderB = new Order(itemB, (15 + 20) - 10);
HashSet<Order> expected = new HashSet<>();
expected.add(expectedOrderA);
expected.add(expectedOrderB);
assertEquals(expected, new HashSet<>(actualOrders));
}
@Test
public void refillSeasonalOnSaleStockWithSaleRefillHigher(){
// given
int onHand = 5;
int shouldHave = 6;
final boolean isRestricted = false;
final Season season = Season.Summer;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals((shouldHave + 20) - onHand, actualOrders.get(0).quantity);
assertEquals(item, actualOrders.get(0).item);
}
@Test
public void refillSeasonalOnSaleStockWithSeasonRefillHigher(){
// given
int onHand = 22;
int shouldHave = 25;
final boolean isRestricted = false;
final Season season = Season.Summer;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals((shouldHave * 2) - onHand, actualOrders.get(0).quantity);
assertEquals(item, actualOrders.get(0).item);
}
@Test
public void doNotRefillDateRestrictedRegularStock(){
// given
int onHand = 22;
int shouldHave = 25;
boolean isRestricted = true;
final Season season = Season.Spring;
Item item = new StockedItem(shouldHave, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 2);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
}
@Test
public void refillDateRestrictedRegularStock(){
// given
int onHand = 22;
int shouldHave = 25;
boolean isRestricted = true;
final Season season = Season.Spring;
Item item = new StockedItem(shouldHave, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 1);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(shouldHave - onHand, actualOrders.get(0).quantity);
}
@Test
public void refillMultipleDateRestrictedRegularStock(){
// given
int onHandA = 22;
int onHandB = 10;
int shouldHaveA = 25;
int shouldHaveB = 15;
boolean isRestricted = true;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(itemA, onHandA);
store.put(itemB, onHandB);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 1);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
final Order expectedOrderA = new Order(itemA, shouldHaveA - onHandA);
final Order expectedOrderB = new Order(itemB, shouldHaveB - onHandB);
HashSet<Order> expected = new HashSet<>();
expected.add(expectedOrderA);
expected.add(expectedOrderB);
assertEquals(expected, new HashSet<>(actualOrders));
}
@Test
public void refillDateRestrictedSaleStock(){
// given
int onHand = 22;
int shouldHave = 25;
boolean isRestricted = true;
Item item = new StockedItem(shouldHave, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 1);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(shouldHave + 20 - onHand, actualOrders.get(0).quantity);
}
@Test
public void doNotRefillDateRestrictedSeasonalStock(){
// given
int onHand = 5;
int shouldHave = 10;
boolean isRestricted = true;
final Season season = Season.Summer;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 2);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
}
@Test
public void refillDateRestrictedSeasonalStock(){
// given
int onHand = 5;
int shouldHave = 10;
boolean isRestricted = true;
final Season season = Season.Summer;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 1);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(shouldHave * 2 - onHand, actualOrders.get(0).quantity);
assertEquals(item, actualOrders.get(0).item);
}
}
| src/test/java/test/com/cjpowered/learn/inventory/InventoryTest.java | package test.com.cjpowered.learn.inventory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import com.cjpowered.learn.inventory.InventoryDatabase;
import com.cjpowered.learn.inventory.InventoryManager;
import com.cjpowered.learn.inventory.Item;
import com.cjpowered.learn.inventory.Order;
import com.cjpowered.learn.inventory.StockedItem;
import com.cjpowered.learn.inventory.ace.AceInventoryManager;
import com.cjpowered.learn.marketing.MarketingInfo;
import com.cjpowered.learn.marketing.Season;
/*
* We need to keep items in stock to prevent back orders. See the README.md
* for the requirements.
*
*/
public class InventoryTest {
@Test
public void doNotRefillStockWhenNoOrders() {
// given
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public List<Item> stockItems(){
return Collections.emptyList();
}
};
final LocalDate today = LocalDate.now();
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return null;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertTrue(actualOrders.isEmpty());
}
@Test
public void refillSingleStock(){
// given
int onHand = 10;
int shouldHave = 16;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(item, actualOrders.get(0).item);
assertEquals(shouldHave - onHand, actualOrders.get(0).quantity);
}
@Test
public void doNotRefillSingleStockSurplus(){
// given
int onHand = 16;
int shouldHave = 10;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return onHand;
}
@Override
public List<Item> stockItems(){
return Collections.singletonList(item);
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
assertTrue(actualOrders.isEmpty());
}
@Test
public void doNotRefillStockPerfectCount(){
// given
int onHand = 10;
int shouldHave = 10;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return onHand;
}
@Override
public List<Item> stockItems(){
return Collections.singletonList(item);
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
assertTrue(actualOrders.isEmpty());
}
@Test
public void refillMultipleStock(){
// given
int onHandA = 10;
int onHandB = 12;
int shouldHaveA = 16;
int shouldHaveB = 20;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
assertEquals(itemA, actualOrders.get(0).item);
assertEquals(itemB, actualOrders.get(1).item);
assertEquals(shouldHaveA - onHandA, actualOrders.get(0).quantity);
assertEquals(shouldHaveB - onHandB, actualOrders.get(1).quantity);
}
@Test
public void refillMultipleStockOneOnly(){
// given
int onHandA = 10;
int onHandB = 12;
int shouldHaveA = 8;
int shouldHaveB = 20;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(itemB, actualOrders.get(0).item);
assertEquals(shouldHaveB - onHandB, actualOrders.get(0).quantity);
}
@Test(expected=IndexOutOfBoundsException.class)
public void doNotRefillInvalidStockOnMultipleOrder(){
// given
int onHandA = 10;
int onHandB = 12;
int shouldHaveA = 8;
int shouldHaveB = 20;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
Item nonExistantItem = actualOrders.get(1).item;
}
@Test
public void refillSaleStock(){
// given
int onHand = 10;
int shouldHave = 15;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return onHand;
}
@Override
public List<Item> stockItems(){
return Collections.singletonList(item);
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(shouldHave - onHand + 20, actualOrders.get(0).quantity);
}
@Test
public void doNotRefillSaleStockPerfectCount(){
// given
int onHand = 35;
int shouldHave = 15;
boolean isRestricted = false;
Item item = new StockedItem(shouldHave, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return onHand;
}
@Override
public List<Item> stockItems(){
return Collections.singletonList(item);
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
}
@Test
public void refillMultipleSaleStock(){
// given
int onHandA = 34;
int onHandB = 34;
int shouldHaveA = 15;
int shouldHaveB = 15;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
assertEquals(itemA, actualOrders.get(0).item);
assertEquals(itemB, actualOrders.get(1).item);
assertEquals(shouldHaveA - onHandA + 20, actualOrders.get(0).quantity);
assertEquals(shouldHaveB - onHandB + 20, actualOrders.get(1).quantity);
}
@Test
public void refillMixStockSaleAndRegular(){
// given
int onHandA = 30;
int onHandB = 14;
int shouldHaveA = 15;
int shouldHaveB = 18;
boolean isRestricted = false;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final InventoryDatabase db = new DatabaseTemplate() {
@Override
public int onHand(Item item){
return item == itemA ? onHandA : onHandB;
}
@Override
public List<Item> stockItems(){
List<Item> items = new ArrayList<Item>();
items.add(itemA);
items.add(itemB);
return items;
}
};
final MarketingInfo mrktInfo = new MarketingInfo(){
@Override
public boolean onSale(Item item) {
return item == itemA ? true : false;
}
@Override
public Season season(LocalDate when) {
return Season.Spring;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
assertEquals(itemA, actualOrders.get(0).item);
assertEquals(itemB, actualOrders.get(1).item);
assertEquals(shouldHaveA - onHandA + 20, actualOrders.get(0).quantity);
assertEquals(shouldHaveB - onHandB, actualOrders.get(1).quantity);
}
@Test
public void refillSingleSeasonalStock(){
// given
int onHand = 10;
int shouldHave = 16;
final Season season = Season.Summer;
final boolean isRestricted = false;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(item, actualOrders.get(0).item);
assertEquals((shouldHave * 2) - onHand, actualOrders.get(0).quantity);
}
@Test
public void doNotRefillSingleSeasonalStock(){
// given
int onHand = 40;
int shouldHave = 20;
final Season season = Season.Summer;
final boolean isRestricted = false;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
}
@Test
public void refillMultipleSeasonalStock(){
// given
int onHandA = 39;
int shouldHaveA = 20;
int onHandB = 21;
int shouldHaveB = 15;
final Season season = Season.Summer;
final boolean isRestricted = false;
Item itemA = new SeasonalItem(shouldHaveA, season, isRestricted);
Item itemB = new SeasonalItem(shouldHaveB, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(itemA, onHandA);
store.put(itemB, onHandB);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
final Order expectedOrderA = new Order(itemA, (2 * 20) - 39);
final Order expectedOrderB = new Order(itemB, (2 * 15) - 21);
HashSet<Order> expected = new HashSet<>();
expected.add(expectedOrderA);
expected.add(expectedOrderB);
assertEquals(expected, new HashSet<>(actualOrders));
}
@Test
public void refillMixStockSeasonalAndRegular(){
// given
int onHandA = 39;
int shouldHaveA = 20;
int onHandB = 10;
int shouldHaveB = 15;
final Season seasonA = Season.Summer;
final Season seasonB = Season.Spring;
boolean isRestricted = false;
Item itemA = new SeasonalItem(shouldHaveA, seasonA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(itemA, onHandA);
store.put(itemB, onHandB);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
final Order expectedOrderA = new Order(itemA, (2 * 20) - 39);
final Order expectedOrderB = new Order(itemB, 15 - 10);
HashSet<Order> expected = new HashSet<>();
expected.add(expectedOrderA);
expected.add(expectedOrderB);
assertEquals(expected, new HashSet<>(actualOrders));
}
@Test
public void refillMixStockSeasonalAndSale(){
// given
int onHandA = 39;
int shouldHaveA = 20;
int onHandB = 10;
int shouldHaveB = 15;
final Season season = Season.Summer;
boolean isRestricted = false;
Item itemA = new SeasonalItem(shouldHaveA, season, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(itemA, onHandA);
store.put(itemB, onHandB);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return item == itemB ? true : false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
final Order expectedOrderA = new Order(itemA, (2 * 20) - 39);
final Order expectedOrderB = new Order(itemB, (15 + 20) - 10);
HashSet<Order> expected = new HashSet<>();
expected.add(expectedOrderA);
expected.add(expectedOrderB);
assertEquals(expected, new HashSet<>(actualOrders));
}
@Test
public void refillSeasonalOnSaleStockWithSaleRefillHigher(){
// given
int onHand = 5;
int shouldHave = 6;
final boolean isRestricted = false;
final Season season = Season.Summer;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals((shouldHave + 20) - onHand, actualOrders.get(0).quantity);
assertEquals(item, actualOrders.get(0).item);
}
@Test
public void refillSeasonalOnSaleStockWithSeasonRefillHigher(){
// given
int onHand = 22;
int shouldHave = 25;
final boolean isRestricted = false;
final Season season = Season.Summer;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.now();
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals((shouldHave * 2) - onHand, actualOrders.get(0).quantity);
assertEquals(item, actualOrders.get(0).item);
}
@Test
public void doNotRefillDateRestrictedRegularStock(){
// given
int onHand = 22;
int shouldHave = 25;
boolean isRestricted = true;
final Season season = Season.Spring;
Item item = new StockedItem(shouldHave, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 2);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
}
@Test
public void refillDateRestrictedRegularStock(){
// given
int onHand = 22;
int shouldHave = 25;
boolean isRestricted = true;
final Season season = Season.Spring;
Item item = new StockedItem(shouldHave, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 1);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(shouldHave - onHand, actualOrders.get(0).quantity);
}
@Test
public void refillMultipleDateRestrictedRegularStock(){
// given
int onHandA = 22;
int onHandB = 10;
int shouldHaveA = 25;
int shouldHaveB = 15;
boolean isRestricted = true;
Item itemA = new StockedItem(shouldHaveA, isRestricted);
Item itemB = new StockedItem(shouldHaveB, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(itemA, onHandA);
store.put(itemB, onHandB);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return false;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 1);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(2, actualOrders.size());
final Order expectedOrderA = new Order(itemA, shouldHaveA - onHandA);
final Order expectedOrderB = new Order(itemB, shouldHaveB - onHandB);
HashSet<Order> expected = new HashSet<>();
expected.add(expectedOrderA);
expected.add(expectedOrderB);
assertEquals(expected, new HashSet<>(actualOrders));
}
@Test
public void refillDateRestrictedSaleStock(){
// given
int onHand = 22;
int shouldHave = 25;
boolean isRestricted = true;
Item item = new StockedItem(shouldHave, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 1);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(1, actualOrders.size());
assertEquals(shouldHave + 20 - onHand, actualOrders.get(0).quantity);
}
@Test
public void doNotRefillDateRestrictedSeasonalStock(){
// given
int onHand = 5;
int shouldHave = 10;
boolean isRestricted = true;
final Season season = Season.Summer;
Item item = new SeasonalItem(shouldHave, season, isRestricted);
final HashMap<Item, Integer> store = new HashMap<>();
store.put(item, onHand);
final InventoryDatabase db = new FakeDatabase(store);
final MarketingInfo mrktInfo = new MarketingTemplate(){
@Override
public boolean onSale(Item item) {
return true;
}
@Override
public Season season(LocalDate when) {
return Season.Summer;
}
};
final InventoryManager im = new AceInventoryManager(db, mrktInfo);
final LocalDate today = LocalDate.of(2017, 1, 2);
// when
final List<Order> actualOrders = im.getOrders(today);
// then
assertEquals(0, actualOrders.size());
}
}
| add test refill restricted seasonal stock
| src/test/java/test/com/cjpowered/learn/inventory/InventoryTest.java | add test refill restricted seasonal stock |
|
Java | mit | 78414d1d48051ff94137d61c247d7f7289e2578b | 0 | citrix/ShareFile-Java,citrix/ShareFile-Java | package com.sharefile.api.enumerations;
import java.net.URI;
import com.sharefile.api.constants.SFKeywords;
import com.sharefile.api.constants.SFSDK;
import com.sharefile.java.log.SLog;
/**
* toString of this will return complete provider with API version alongwith slashes: "/cifs/v3/", "/sp/v3/", "/sf/v3/",... etc
*/
public enum SFProvider
{
PROVIDER_TYPE_SF("/sf/"+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH),
PROVIDER_TYPE_CIFS("/cifs/"+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH),
PROVIDER_TYPE_SHAREPOINT("/sp/"+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH),
PROVIDER_TYPE_PROXYSERVICE("/ProxyService/"+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH);
private static final String keywordV3 = SFKeywords.FWD_SLASH+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH;
private static final String TAG = SFKeywords.TAG + "-getProvider";
private final String mToStr;
private SFProvider(String toStr)
{
mToStr = toStr;
}
@Override
public String toString()
{
return mToStr;
}
/**
* String can be of type :
* <p>https://szqatest2.sharefiletest.com/cifs/v3/Items(4L24TVJSEz6Ca22LWoZg41hIVgfFgqQx0GD2VoYSgXA_)</p>
*
* or
* <p>
* "https://szqatest2.sharefiletest.com/sp/upload-streaming-2.aspx?uploadid=rsu-27564a05c0cf4052989099f3e880afda&parentid
*
* <p>This function finds the provider based on the occurence of /sf/v3/ , /sp/v3/ , /cifs/v3/ whichever occurs first
*
* We check all of them since multiple of them may occur in a given string, but the first occurence defines the provider type
*/
public static SFProvider getProviderType(String str)
{
SFProvider provider = PROVIDER_TYPE_SF; //return sf by default so as not to cause NullPointer exceptions
//for bad strings.
if(str!=null)
{
/*
* look for the first occurence of "/v3/" and then look to the left of it.
* this way we don't waste too much time in string comparison.
*/
int indexOfV3 = str.indexOf(keywordV3);
if(indexOfV3 == -1)
{
indexOfV3 = str.indexOf("/upload-streaming");
if(indexOfV3 == -1) // is needed or the uploafd to connectors wont work.
{
return provider;
}
}
try
{
//HACK optimize: look for the first chracter before this index since. can change this later if things break.
switch(str.charAt(indexOfV3-1))
{
case 'p': provider = PROVIDER_TYPE_SHAREPOINT;
break;
case 'f': provider = PROVIDER_TYPE_SF;
break;
case 's': provider = PROVIDER_TYPE_CIFS;
break;
case 'e': provider = PROVIDER_TYPE_PROXYSERVICE;
break;
}
}
catch(Exception ex)
{
SLog.d(TAG, "!!!Exception getting provider type from: " + str, ex);
}
}
SLog.d(TAG, "Returning provider type = %s" + provider.toString());
return provider;
}
public static SFProvider getProviderType(URI uri)
{
String str = null;
if(uri!=null)
{
str = uri.toString();
}
return getProviderType(str);
}
} | CoreSFV3SDK/src/com/sharefile/api/enumerations/SFProvider.java | package com.sharefile.api.enumerations;
import java.net.URI;
import com.sharefile.api.constants.SFKeywords;
import com.sharefile.api.constants.SFSDK;
import com.sharefile.java.log.SLog;
/**
* toString of this will return complete provider with API version alongwith slashes: "/cifs/v3/", "/sp/v3/", "/sf/v3/",... etc
*/
public enum SFProvider
{
PROVIDER_TYPE_SF("/sf/"+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH),
PROVIDER_TYPE_CIFS("/cifs/"+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH),
PROVIDER_TYPE_SHAREPOINT("/sp/"+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH),
PROVIDER_TYPE_PROXYSERVICE("/ProxyService/"+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH);
private static final String keywordV3 = SFKeywords.FWD_SLASH+SFSDK.VERSION_FOR_QUERY_URL+ SFKeywords.FWD_SLASH;
private static final String TAG = SFKeywords.TAG + "-getProvider";
private final String mToStr;
private SFProvider(String toStr)
{
mToStr = toStr;
}
@Override
public String toString()
{
return mToStr;
}
/**
* String can be of type :
* <p>https://szqatest2.sharefiletest.com/cifs/v3/Items(4L24TVJSEz6Ca22LWoZg41hIVgfFgqQx0GD2VoYSgXA_)</p>
*
* or
* <p>
* "https://szqatest2.sharefiletest.com/sp/upload-streaming-2.aspx?uploadid=rsu-27564a05c0cf4052989099f3e880afda&parentid
*
* <p>This function finds the provider based on the occurence of /sf/v3/ , /sp/v3/ , /cifs/v3/ whichever occurs first
*
* We check all of them since multiple of them may occur in a given string, but the first occurence defines the provider type
*/
public static SFProvider getProviderType(String str)
{
SFProvider provider = PROVIDER_TYPE_SF; //return sf by default so as not to cause NullPointer exceptions
//for bad strings.
if(str!=null)
{
/*
* look for the first occurence of "/v3/" and then look to the left of it.
* this way we don't waste too much time in string comparison.
*/
int indexOfV3 = str.indexOf(keywordV3);
if(indexOfV3 == -1)
{
indexOfV3 = str.indexOf("/upload-streaming");
return provider;
}
try
{
//HACK optimize: look for the first chracter before this index since. can change this later if things break.
switch(str.charAt(indexOfV3-1))
{
case 'p': provider = PROVIDER_TYPE_SHAREPOINT;
break;
case 'f': provider = PROVIDER_TYPE_SF;
break;
case 's': provider = PROVIDER_TYPE_CIFS;
break;
case 'e': provider = PROVIDER_TYPE_PROXYSERVICE;
break;
}
}
catch(Exception ex)
{
SLog.d(TAG, "!!!Exception getting provider type from: " + str, ex);
}
}
SLog.d(TAG, "Returning provider type = %s" + provider.toString());
return provider;
}
public static SFProvider getProviderType(URI uri)
{
String str = null;
if(uri!=null)
{
str = uri.toString();
}
return getProviderType(str);
}
} | Fix the getProviderType
| CoreSFV3SDK/src/com/sharefile/api/enumerations/SFProvider.java | Fix the getProviderType |
|
Java | mit | b0cee711d9e29da131b2288c6c7cc8485204f038 | 0 | pkwenda/webBee,java-webbee/webBee | package org.bee.webBee.utils;
/**
* data 2017-05-11 01:25
* E-mail [email protected]
* 封装下载文件需要的函数
* @author sis.nonacosa
*/
public class DownFileUtil {
}
| webBee-core/src/main/java/org/bee/webBee/utils/DownFileUtil.java | package org.bee.webBee.utils;
/**
* data 2017-05-11 01:25
* E-mail [email protected]
* 封装下载文件需要的函数
* @author sis.nonacosa
*/
public class DownFileUtil {
}
| del annocation code
del annocation code
| webBee-core/src/main/java/org/bee/webBee/utils/DownFileUtil.java | del annocation code |
|
Java | mit | 4627bb2bfc429d01947e9f134cf5685a8181f0ca | 0 | fimkrypto/nxt,fimkrypto/nxt,fimkrypto/nxt,Ziftr/nxt,Ziftr/nxt,fimkrypto/nxt,Ziftr/nxt | package nxt.db;
import nxt.Nxt;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class EntityDbTable<T> extends DerivedDbTable {
private final boolean multiversion;
protected final DbKey.Factory<T> dbKeyFactory;
private final String defaultSort;
protected EntityDbTable(String table, DbKey.Factory<T> dbKeyFactory) {
this(table, dbKeyFactory, false);
}
EntityDbTable(String table, DbKey.Factory<T> dbKeyFactory, boolean multiversion) {
super(table);
this.dbKeyFactory = dbKeyFactory;
this.multiversion = multiversion;
this.defaultSort = " ORDER BY " + (multiversion ? dbKeyFactory.getPKColumns() : " height DESC ");
}
protected abstract T load(Connection con, ResultSet rs) throws SQLException;
protected abstract void save(Connection con, T t) throws SQLException;
protected String defaultSort() {
return defaultSort;
}
public final void checkAvailable(int height) {
if (multiversion && height < Nxt.getBlockchainProcessor().getMinRollbackHeight()) {
throw new IllegalArgumentException("Historical data as of height " + height +" not available, set nxt.trimDerivedTables=false and re-scan");
}
}
public final T get(DbKey dbKey) {
if (db.isInTransaction()) {
T t = (T) db.getCache(table).get(dbKey);
if (t != null) {
return t;
}
}
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + dbKeyFactory.getPKClause()
+ (multiversion ? " AND latest = TRUE LIMIT 1" : ""))) {
dbKey.setPK(pstmt);
return get(con, pstmt, true);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final T get(DbKey dbKey, int height) {
checkAvailable(height);
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + dbKeyFactory.getPKClause()
+ " AND height <= ?" + (multiversion ? " AND (latest = TRUE OR EXISTS ("
+ "SELECT 1 FROM " + table + dbKeyFactory.getPKClause() + " AND height > ?)) ORDER BY height DESC LIMIT 1" : ""))) {
int i = dbKey.setPK(pstmt);
pstmt.setInt(i, height);
if (multiversion) {
i = dbKey.setPK(pstmt, ++i);
pstmt.setInt(i, height);
}
return get(con, pstmt, false);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final T getBy(DbClause dbClause) {
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table
+ " WHERE " + dbClause.getClause() + (multiversion ? " AND latest = TRUE LIMIT 1" : ""))) {
dbClause.set(pstmt, 1);
return get(con, pstmt, true);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final T getBy(DbClause dbClause, int height) {
checkAvailable(height);
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + " AS a WHERE " + dbClause.getClause()
+ " AND height <= ?" + (multiversion ? " AND (latest = TRUE OR EXISTS ("
+ "SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause()
+ " AND b.height > ?)) ORDER BY height DESC LIMIT 1" : ""))) {
int i = 0;
i = dbClause.set(pstmt, ++i);
pstmt.setInt(i, height);
if (multiversion) {
pstmt.setInt(++i, height);
}
return get(con, pstmt, false);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
private T get(Connection con, PreparedStatement pstmt, boolean cache) throws SQLException {
final boolean doCache = cache && db.isInTransaction();
try (ResultSet rs = pstmt.executeQuery()) {
if (!rs.next()) {
return null;
}
T t = null;
DbKey dbKey = null;
if (doCache) {
dbKey = dbKeyFactory.newKey(rs);
t = (T) db.getCache(table).get(dbKey);
}
if (t == null) {
t = load(con, rs);
if (doCache) {
db.getCache(table).put(dbKey, t);
}
}
if (rs.next()) {
throw new RuntimeException("Multiple records found");
}
return t;
}
}
public final DbIterator<T> getManyBy(DbClause dbClause, int from, int to) {
return getManyBy(dbClause, from, to, defaultSort());
}
public final DbIterator<T> getManyBy(DbClause dbClause, int from, int to, String sort) {
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table
+ " WHERE " + dbClause.getClause() + (multiversion ? " AND latest = TRUE " : " ") + sort
+ DbUtils.limitsClause(from, to));
int i = 0;
i = dbClause.set(pstmt, ++i);
i = DbUtils.setLimits(i, pstmt, from, to);
return getManyBy(con, pstmt, true);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final DbIterator<T> getManyBy(DbClause dbClause, int height, int from, int to) {
return getManyBy(dbClause, height, from, to, defaultSort());
}
public final DbIterator<T> getManyBy(DbClause dbClause, int height, int from, int to, String sort) {
checkAvailable(height);
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + " AS a WHERE " + dbClause.getClause()
+ "AND a.height <= ?" + (multiversion ? " AND (a.latest = TRUE OR (a.latest = FALSE "
+ "AND EXISTS (SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause() + " AND b.height > ?) "
+ "AND NOT EXISTS (SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause()
+ " AND b.height <= ? AND b.height > a.height))) "
: " ") + sort
+ DbUtils.limitsClause(from, to));
int i = 0;
i = dbClause.set(pstmt, ++i);
pstmt.setInt(i, height);
if (multiversion) {
pstmt.setInt(++i, height);
pstmt.setInt(++i, height);
}
i = DbUtils.setLimits(++i, pstmt, from, to);
return getManyBy(con, pstmt, false);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final DbIterator<T> getManyBy(Connection con, PreparedStatement pstmt, boolean cache) {
final boolean doCache = cache && db.isInTransaction();
return new DbIterator<>(con, pstmt, new DbIterator.ResultSetReader<T>() {
@Override
public T get(Connection con, ResultSet rs) throws Exception {
T t = null;
DbKey dbKey = null;
if (doCache) {
dbKey = dbKeyFactory.newKey(rs);
t = (T) db.getCache(table).get(dbKey);
}
if (t == null) {
t = load(con, rs);
if (doCache) {
db.getCache(table).put(dbKey, t);
}
}
return t;
}
});
}
public final DbIterator<T> search(String query, DbClause dbClause, int from, int to) {
return search(query, dbClause, from, to, " ORDER BY ft.score DESC ");
}
public final DbIterator<T> search(String query, DbClause dbClause, int from, int to, String sort) {
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT " + table + ".*, ft.score FROM " + table + ", ftl_search_data(?, 2147483647, 0) ft "
+ " WHERE " + table + ".db_id = ft.keys[0] AND ft.table = ? " + (multiversion ? " AND " + table + ".latest = TRUE " : " ")
+ " AND " + dbClause.getClause() + sort
+ DbUtils.limitsClause(from, to));
int i = 0;
pstmt.setString(++i, query);
pstmt.setString(++i, table.toUpperCase());
i = dbClause.set(pstmt, ++i);
i = DbUtils.setLimits(i, pstmt, from, to);
return getManyBy(con, pstmt, true);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final DbIterator<T> getAll(int from, int to) {
return getAll(from, to, defaultSort());
}
public final DbIterator<T> getAll(int from, int to, String sort) {
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table
+ (multiversion ? " WHERE latest = TRUE " : " ") + sort
+ DbUtils.limitsClause(from, to));
DbUtils.setLimits(1, pstmt, from, to);
return getManyBy(con, pstmt, true);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final DbIterator<T> getAll(int height, int from, int to) {
return getAll(height, from, to, defaultSort());
}
public final DbIterator<T> getAll(int height, int from, int to, String sort) {
checkAvailable(height);
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + " AS a WHERE height <= ?"
+ (multiversion ? " AND (latest = TRUE OR (latest = FALSE "
+ "AND EXISTS (SELECT 1 FROM " + table + " AS b WHERE b.height > ? AND " + dbKeyFactory.getSelfJoinClause()
+ ") AND NOT EXISTS (SELECT 1 FROM " + table + " AS b WHERE b.height <= ? AND " + dbKeyFactory.getSelfJoinClause()
+ " AND b.height > a.height))) " : " ") + sort
+ DbUtils.limitsClause(from, to));
int i = 0;
pstmt.setInt(++i, height);
if (multiversion) {
pstmt.setInt(++i, height);
pstmt.setInt(++i, height);
}
i = DbUtils.setLimits(++i, pstmt, from, to);
return getManyBy(con, pstmt, false);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final int getCount() {
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT COUNT(*) FROM " + table
+ (multiversion ? " WHERE latest = TRUE" : ""))) {
return getCount(pstmt);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final int getCount(DbClause dbClause) {
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT COUNT(*) FROM " + table
+ " WHERE " + dbClause.getClause() + (multiversion ? " AND latest = TRUE" : ""))) {
dbClause.set(pstmt, 1);
return getCount(pstmt);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final int getCount(DbClause dbClause, int height) {
checkAvailable(height);
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT COUNT(*) FROM " + table + " AS a WHERE " + dbClause.getClause()
+ "AND a.height <= ?" + (multiversion ? " AND (a.latest = TRUE OR (a.latest = FALSE "
+ "AND EXISTS (SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause() + " AND b.height > ?) "
+ "AND NOT EXISTS (SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause()
+ " AND b.height <= ? AND b.height > a.height))) "
: " "));
int i = 0;
i = dbClause.set(pstmt, ++i);
pstmt.setInt(i, height);
if (multiversion) {
pstmt.setInt(++i, height);
pstmt.setInt(++i, height);
}
return getCount(pstmt);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final int getRowCount() {
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT COUNT(*) FROM " + table)) {
return getCount(pstmt);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
private int getCount(PreparedStatement pstmt) throws SQLException {
try (ResultSet rs = pstmt.executeQuery()) {
rs.next();
return rs.getInt(1);
}
}
public final void insert(T t) {
if (!db.isInTransaction()) {
throw new IllegalStateException("Not in transaction");
}
DbKey dbKey = dbKeyFactory.newKey(t);
T cachedT = (T) db.getCache(table).get(dbKey);
if (cachedT == null) {
db.getCache(table).put(dbKey, t);
} else if (t != cachedT) { // not a bug
throw new IllegalStateException("Different instance found in Db cache, perhaps trying to save an object "
+ "that was read outside the current transaction");
}
try (Connection con = db.getConnection()) {
if (multiversion) {
try (PreparedStatement pstmt = con.prepareStatement("UPDATE " + table
+ " SET latest = FALSE " + dbKeyFactory.getPKClause() + " AND latest = TRUE LIMIT 1")) {
dbKey.setPK(pstmt);
pstmt.executeUpdate();
}
}
save(con, t);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
@Override
public void rollback(int height) {
super.rollback(height);
db.getCache(table).clear();
}
@Override
public final void truncate() {
super.truncate();
db.getCache(table).clear();
}
}
| src/java/nxt/db/EntityDbTable.java | package nxt.db;
import nxt.Nxt;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class EntityDbTable<T> extends DerivedDbTable {
private final boolean multiversion;
protected final DbKey.Factory<T> dbKeyFactory;
private final String defaultSort;
protected EntityDbTable(String table, DbKey.Factory<T> dbKeyFactory) {
this(table, dbKeyFactory, false);
}
EntityDbTable(String table, DbKey.Factory<T> dbKeyFactory, boolean multiversion) {
super(table);
this.dbKeyFactory = dbKeyFactory;
this.multiversion = multiversion;
this.defaultSort = " ORDER BY " + (multiversion ? dbKeyFactory.getPKColumns() : " height DESC ");
}
protected abstract T load(Connection con, ResultSet rs) throws SQLException;
protected abstract void save(Connection con, T t) throws SQLException;
protected String defaultSort() {
return defaultSort;
}
public final void checkAvailable(int height) {
if (multiversion && height < Nxt.getBlockchainProcessor().getMinRollbackHeight()) {
throw new IllegalArgumentException("Historical data as of height " + height +" not available, set nxt.trimDerivedTables=false and re-scan");
}
}
public final T get(DbKey dbKey) {
if (db.isInTransaction()) {
T t = (T) db.getCache(table).get(dbKey);
if (t != null) {
return t;
}
}
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + dbKeyFactory.getPKClause()
+ (multiversion ? " AND latest = TRUE LIMIT 1" : ""))) {
dbKey.setPK(pstmt);
return get(con, pstmt, true);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final T get(DbKey dbKey, int height) {
checkAvailable(height);
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + dbKeyFactory.getPKClause()
+ " AND height <= ?" + (multiversion ? " AND (latest = TRUE OR EXISTS ("
+ "SELECT 1 FROM " + table + dbKeyFactory.getPKClause() + " AND height > ?)) ORDER BY height DESC LIMIT 1" : ""))) {
int i = dbKey.setPK(pstmt);
pstmt.setInt(i, height);
if (multiversion) {
i = dbKey.setPK(pstmt, ++i);
pstmt.setInt(i, height);
}
return get(con, pstmt, false);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final T getBy(DbClause dbClause) {
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table
+ " WHERE " + dbClause.getClause() + (multiversion ? " AND latest = TRUE LIMIT 1" : ""))) {
dbClause.set(pstmt, 1);
return get(con, pstmt, true);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final T getBy(DbClause dbClause, int height) {
checkAvailable(height);
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + " AS a WHERE " + dbClause.getClause()
+ " AND height <= ?" + (multiversion ? " AND (latest = TRUE OR EXISTS ("
+ "SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause()
+ " AND b.height > ?)) ORDER BY height DESC LIMIT 1" : ""))) {
int i = 0;
i = dbClause.set(pstmt, ++i);
pstmt.setInt(i, height);
if (multiversion) {
pstmt.setInt(++i, height);
}
return get(con, pstmt, false);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
private T get(Connection con, PreparedStatement pstmt, boolean cache) throws SQLException {
final boolean doCache = cache && db.isInTransaction();
try (ResultSet rs = pstmt.executeQuery()) {
if (!rs.next()) {
return null;
}
T t = null;
DbKey dbKey = null;
if (doCache) {
dbKey = dbKeyFactory.newKey(rs);
t = (T) db.getCache(table).get(dbKey);
}
if (t == null) {
t = load(con, rs);
if (doCache) {
db.getCache(table).put(dbKey, t);
}
}
if (rs.next()) {
throw new RuntimeException("Multiple records found");
}
return t;
}
}
public final DbIterator<T> getManyBy(DbClause dbClause, int from, int to) {
return getManyBy(dbClause, from, to, defaultSort());
}
public final DbIterator<T> getManyBy(DbClause dbClause, int from, int to, String sort) {
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table
+ " WHERE " + dbClause.getClause() + (multiversion ? " AND latest = TRUE " : " ") + sort
+ DbUtils.limitsClause(from, to));
int i = 0;
i = dbClause.set(pstmt, ++i);
i = DbUtils.setLimits(i, pstmt, from, to);
return getManyBy(con, pstmt, true);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final DbIterator<T> getManyBy(DbClause dbClause, int height, int from, int to) {
return getManyBy(dbClause, height, from, to, defaultSort());
}
public final DbIterator<T> getManyBy(DbClause dbClause, int height, int from, int to, String sort) {
checkAvailable(height);
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + " AS a WHERE " + dbClause.getClause()
+ "AND a.height <= ?" + (multiversion ? " AND (a.latest = TRUE OR (a.latest = FALSE "
+ "AND EXISTS (SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause() + " AND b.height > ?) "
+ "AND NOT EXISTS (SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause()
+ " AND b.height <= ? AND b.height > a.height))) "
: " ") + sort
+ DbUtils.limitsClause(from, to));
int i = 0;
i = dbClause.set(pstmt, ++i);
pstmt.setInt(i, height);
if (multiversion) {
pstmt.setInt(++i, height);
pstmt.setInt(++i, height);
}
i = DbUtils.setLimits(++i, pstmt, from, to);
return getManyBy(con, pstmt, false);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final DbIterator<T> getManyBy(Connection con, PreparedStatement pstmt, boolean cache) {
final boolean doCache = cache && db.isInTransaction();
return new DbIterator<>(con, pstmt, new DbIterator.ResultSetReader<T>() {
@Override
public T get(Connection con, ResultSet rs) throws Exception {
T t = null;
DbKey dbKey = null;
if (doCache) {
dbKey = dbKeyFactory.newKey(rs);
t = (T) db.getCache(table).get(dbKey);
}
if (t == null) {
t = load(con, rs);
if (doCache) {
db.getCache(table).put(dbKey, t);
}
}
return t;
}
});
}
public final DbIterator<T> search(String query, DbClause dbClause, int from, int to) {
return search(query, dbClause, from, to, " ORDER BY ft.score DESC ");
}
public final DbIterator<T> search(String query, DbClause dbClause, int from, int to, String sort) {
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT " + table + ".*, ft.score FROM " + table + ", ftl_search_data(?, 0, 0) ft "
+ " WHERE " + table + ".db_id = ft.keys[0] AND ft.table = ? " + (multiversion ? " AND " + table + ".latest = TRUE " : " ")
+ " AND " + dbClause.getClause() + sort
+ DbUtils.limitsClause(from, to));
int i = 0;
pstmt.setString(++i, query);
pstmt.setString(++i, table.toUpperCase());
i = dbClause.set(pstmt, ++i);
i = DbUtils.setLimits(i, pstmt, from, to);
return getManyBy(con, pstmt, true);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final DbIterator<T> getAll(int from, int to) {
return getAll(from, to, defaultSort());
}
public final DbIterator<T> getAll(int from, int to, String sort) {
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table
+ (multiversion ? " WHERE latest = TRUE " : " ") + sort
+ DbUtils.limitsClause(from, to));
DbUtils.setLimits(1, pstmt, from, to);
return getManyBy(con, pstmt, true);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final DbIterator<T> getAll(int height, int from, int to) {
return getAll(height, from, to, defaultSort());
}
public final DbIterator<T> getAll(int height, int from, int to, String sort) {
checkAvailable(height);
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM " + table + " AS a WHERE height <= ?"
+ (multiversion ? " AND (latest = TRUE OR (latest = FALSE "
+ "AND EXISTS (SELECT 1 FROM " + table + " AS b WHERE b.height > ? AND " + dbKeyFactory.getSelfJoinClause()
+ ") AND NOT EXISTS (SELECT 1 FROM " + table + " AS b WHERE b.height <= ? AND " + dbKeyFactory.getSelfJoinClause()
+ " AND b.height > a.height))) " : " ") + sort
+ DbUtils.limitsClause(from, to));
int i = 0;
pstmt.setInt(++i, height);
if (multiversion) {
pstmt.setInt(++i, height);
pstmt.setInt(++i, height);
}
i = DbUtils.setLimits(++i, pstmt, from, to);
return getManyBy(con, pstmt, false);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final int getCount() {
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT COUNT(*) FROM " + table
+ (multiversion ? " WHERE latest = TRUE" : ""))) {
return getCount(pstmt);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final int getCount(DbClause dbClause) {
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT COUNT(*) FROM " + table
+ " WHERE " + dbClause.getClause() + (multiversion ? " AND latest = TRUE" : ""))) {
dbClause.set(pstmt, 1);
return getCount(pstmt);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
public final int getCount(DbClause dbClause, int height) {
checkAvailable(height);
Connection con = null;
try {
con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT COUNT(*) FROM " + table + " AS a WHERE " + dbClause.getClause()
+ "AND a.height <= ?" + (multiversion ? " AND (a.latest = TRUE OR (a.latest = FALSE "
+ "AND EXISTS (SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause() + " AND b.height > ?) "
+ "AND NOT EXISTS (SELECT 1 FROM " + table + " AS b WHERE " + dbKeyFactory.getSelfJoinClause()
+ " AND b.height <= ? AND b.height > a.height))) "
: " "));
int i = 0;
i = dbClause.set(pstmt, ++i);
pstmt.setInt(i, height);
if (multiversion) {
pstmt.setInt(++i, height);
pstmt.setInt(++i, height);
}
return getCount(pstmt);
} catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public final int getRowCount() {
try (Connection con = db.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT COUNT(*) FROM " + table)) {
return getCount(pstmt);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
private int getCount(PreparedStatement pstmt) throws SQLException {
try (ResultSet rs = pstmt.executeQuery()) {
rs.next();
return rs.getInt(1);
}
}
public final void insert(T t) {
if (!db.isInTransaction()) {
throw new IllegalStateException("Not in transaction");
}
DbKey dbKey = dbKeyFactory.newKey(t);
T cachedT = (T) db.getCache(table).get(dbKey);
if (cachedT == null) {
db.getCache(table).put(dbKey, t);
} else if (t != cachedT) { // not a bug
throw new IllegalStateException("Different instance found in Db cache, perhaps trying to save an object "
+ "that was read outside the current transaction");
}
try (Connection con = db.getConnection()) {
if (multiversion) {
try (PreparedStatement pstmt = con.prepareStatement("UPDATE " + table
+ " SET latest = FALSE " + dbKeyFactory.getPKClause() + " AND latest = TRUE LIMIT 1")) {
dbKey.setPK(pstmt);
pstmt.executeUpdate();
}
}
save(con, t);
} catch (SQLException e) {
throw new RuntimeException(e.toString(), e);
}
}
@Override
public void rollback(int height) {
super.rollback(height);
db.getCache(table).clear();
}
@Override
public final void truncate() {
super.truncate();
db.getCache(table).clear();
}
}
| no limit on search results
| src/java/nxt/db/EntityDbTable.java | no limit on search results |
|
Java | mit | c9de4210b6b7445ed2d7a84fe93777ea1eed3c2b | 0 | CS2103AUG2016-T11-C1/main,CS2103AUG2016-T11-C1/main | //@@author A0144919W
package guitests;
import org.junit.Test;
import seedu.tasklist.commons.core.Messages;
import seedu.tasklist.testutil.TestTask;
import seedu.tasklist.testutil.TestUtil;
import seedu.tasklist.testutil.TypicalTestTasks;
import static org.junit.Assert.assertTrue;
public class FindCommandTest extends TaskListGuiTest {
@Test
public void find_nonEmptyList() {
assertFindResult("find dry", TypicalTestTasks.task3); //no results
assertFindResult("find buy", TypicalTestTasks.task1); //one result
assertFindResult("find complete", TypicalTestTasks.task4, TypicalTestTasks.task6); //more than one matching result
assertFindResult("find *", TypicalTestTasks.task1, TypicalTestTasks.task2, TypicalTestTasks.task3, TypicalTestTasks.task4, TypicalTestTasks.task5, TypicalTestTasks.task6, TypicalTestTasks.task7, TypicalTestTasks.task10, TypicalTestTasks.task11);
//find after adding one result
TestTask[] currentList = td.getTypicalTasks();
currentList = TestUtil.addTasksToList(currentList, TypicalTestTasks.task9);
commandBox.runCommand("add Buy groceries at 10pm p/med");
assertFindResult("find b*y*", TypicalTestTasks.task1, TypicalTestTasks.task9);
//find after deleting one result
commandBox.runCommand("delete 1");
assertFindResult("find buy", TypicalTestTasks.task9);
}
@Test
public void find_emptyList() {
commandBox.runCommand("clear");
assertFindResult("find laundry"); //no results
}
@Test
public void find_invalidCommand_fail() {
commandBox.runCommand("findgeorge");
assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);
}
private void assertFindResult(String command, TestTask... expectedHits ) {
commandBox.runCommand(command);
assertListSize(expectedHits.length);
if (expectedHits.length==0)
assertResultMessage("No such task was found.");
else assertResultMessage(expectedHits.length + " task(s) listed!");
}
}
| src/test/java/guitests/FindCommandTest.java | //@@author A0144919W
package guitests;
import org.junit.Test;
import seedu.tasklist.commons.core.Messages;
import seedu.tasklist.testutil.TestTask;
import seedu.tasklist.testutil.TestUtil;
import seedu.tasklist.testutil.TypicalTestTasks;
import static org.junit.Assert.assertTrue;
public class FindCommandTest extends TaskListGuiTest {
@Test
public void find_nonEmptyList() {
assertFindResult("find dry", TypicalTestTasks.task3); //no results
assertFindResult("find buy", TypicalTestTasks.task1); //one result
assertFindResult("find complete", TypicalTestTasks.task4, TypicalTestTasks.task6); //more than one matching result
assertFindResult("find *", TypicalTestTasks.task1, TypicalTestTasks.task2, TypicalTestTasks.task3, TypicalTestTasks.task4, TypicalTestTasks.task5, TypicalTestTasks.task6, TypicalTestTasks.task7, TypicalTestTasks.task10, TypicalTestTasks.task11);
//find after adding one result
TestTask[] currentList = td.getTypicalTasks();
currentList = TestUtil.addTasksToList(currentList, TypicalTestTasks.task9);
commandBox.runCommand("add Buy groceries at 10pm p/med");
assertFindResult("find b*y*", TypicalTestTasks.task1, TypicalTestTasks.task9);
//find after deleting one result
commandBox.runCommand("delete 1");
assertFindResult("find buy", TypicalTestTasks.task9);
}
@Test
public void find_emptyList(){
commandBox.runCommand("clear");
assertFindResult("find laundry"); //no results
}
@Test
public void find_invalidCommand_fail() {
commandBox.runCommand("findgeorge");
assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);
}
private void assertFindResult(String command, TestTask... expectedHits ) {
commandBox.runCommand(command);
assertListSize(expectedHits.length);
if (expectedHits.length==0)
assertResultMessage("No such task was found.");
else assertResultMessage(expectedHits.length + " task(s) listed!");
}
}
| Very minor coding standard change
| src/test/java/guitests/FindCommandTest.java | Very minor coding standard change |
|
Java | mit | a4c2f5395ec56a733194a1dc49d40d2bde0e6a89 | 0 | Curdled/Algorithms | package uk.ac.cam.josi2.DataStructures;
import java.util.LinkedList;
import java.util.List;
/**
* Created by Joe on 07/04/2015.
*/
public class BTree<T extends Comparable<T>,U> {
private BTreeNode mRoot;
private final int mMinDegree;
public BTree(int minDegree){
mMinDegree = minDegree;
mRoot = new BTreeNode();
}
public U search(T key){
BTreeNode node = mRoot;
while(true){
int i = 0;
//Find the correct node with respect to the key value.
for (; i != node.mKeys.size(); i++) {
KeyDataPair kd = node.mKeys.get(i);
int val = kd.compareTo(key);
if(val == 0) {
return kd.mData;
}
else if(val > 0){
if(node.mLeaf)
return null;
node = node.mPointers.get(i);
break;
}
}
if(!node.mLeaf && i == node.mKeys.size())
node = node.mPointers.get(node.mPointers.size()-1);
}
}
public void insert(T key, U value){
BTreeNode newRoot = mRoot;
KeyDataPair p = new KeyDataPair(key, value);
if (newRoot.mKeys.size() == 2*mMinDegree - 1){
BTreeNode s = new BTreeNode();
mRoot = s;
s.mLeaf = false;
s.mPointers.add(0,newRoot);
s.split(0);
insertNotFull(s, p);
}
else
insertNotFull(newRoot, p);
}
private void insertNotFull(BTreeNode node, KeyDataPair keyDataPair) {
if(node.mLeaf) {
int i = 0;
for (; i != node.mKeys.size(); i++) {
if(node.mKeys.get(i).compareTo(keyDataPair) >= 0){
break;
}
}
node.mKeys.add(i, keyDataPair);
}
else {
int i = 0;
for (; i != node.mKeys.size(); i++) {
if(node.mKeys.get(i).compareTo(keyDataPair) >= 0){
break;
}
}
if(node.mPointers.get(i).mKeys.size() == 2*mMinDegree - 1){
node.split(i);
if(node.mKeys.get(i).compareTo(keyDataPair) < 0)
i++;
}
insertNotFull(node.mPointers.get(i), keyDataPair);
}
}
private class BTreeNode{
private boolean mLeaf;
private List<KeyDataPair> mKeys;
private List<BTreeNode> mPointers;
public BTreeNode(){
mLeaf = true;
mKeys = new LinkedList<>();
mPointers = new LinkedList<>();
}
public void split(int ith){
BTreeNode rightNode = new BTreeNode();
BTreeNode leftNode = this.mPointers.get(ith);
rightNode.mLeaf = leftNode.mLeaf;
//moves all the keys that are the right side of ith to
//the newly created rightNode.
for (int i = 0; i != mMinDegree-1; i++) {
rightNode.mKeys.add(leftNode.mKeys.get(i+mMinDegree));
}
if (!leftNode.mLeaf){
for (int i = 0; i != mMinDegree; i++) {
rightNode.mPointers.add(leftNode.mPointers.get(i+mMinDegree));
}
}
mPointers.add(ith+1, rightNode);
mKeys.add(ith, leftNode.mKeys.get(mMinDegree-1));
for (int i = leftNode.mKeys.size(); i > mMinDegree-1; i--) {
leftNode.mKeys.remove(i-1);
}
for (int i = leftNode.mPointers.size(); i > mMinDegree; i--) {
leftNode.mPointers.remove(i-1);
}
}
}
private class KeyDataPair implements Comparable<KeyDataPair>{
private T mKey;
private U mData;
public KeyDataPair(T key, U value){
mKey = key;
mData = value;
}
@Override
public int compareTo(KeyDataPair o) {
return mKey.compareTo(o.mKey);
}
public int compareTo(T key) {
return mKey.compareTo(key);
}
}
}
| src/uk/ac/cam/josi2/DataStructures/BTree.java | package uk.ac.cam.josi2.DataStructures;
import java.util.LinkedList;
import java.util.List;
/**
* Created by Joe on 07/04/2015.
*/
public class BTree<T extends Comparable<T>,U> {
private BTreeNode mRoot;
private final int mMinDegree;
public BTree(int minDegree){
mMinDegree = minDegree;
mRoot = new BTreeNode();
}
public U search(T key){
BTreeNode node = mRoot;
while(node != null){
for (int i = 0; i != node.mKeys.size(); i++) {
//check left side if not check next one and
//after going through the whole loop
//go down the right side.
int value = node.mKeys.get(i).compareTo(key);
if(value == 0 )//found the value return it.
return node.mKeys.get(i).mData;
else if(value > 0) {//value is left of the key being checked
node = node.mPointers.get(i);
break;
}
}
//value not found so far so must be right of this key
node = node.mPointers.get(node.mPointers.size()-1);
}
return null;
}
public void insert(T key, U value){
BTreeNode newRoot = mRoot;
KeyDataPair p = new KeyDataPair(key, value);
if (newRoot.mKeys.size() == 2*mMinDegree - 1){
BTreeNode s = new BTreeNode();
mRoot = s;
s.mLeaf = false;
s.mPointers.add(0,newRoot);
s.split(0);
insertNotFull(s, p);
}
else
insertNotFull(newRoot, p);
}
private void insertNotFull(BTreeNode node, KeyDataPair keyDataPair) {
if(node.mLeaf) {
int i = 0;
for (; i != node.mKeys.size(); i++) {
if(node.mKeys.get(i).compareTo(keyDataPair) >= 0){
break;
}
}
node.mKeys.add(i, keyDataPair);
}
else {
int i = 0;
for (; i != node.mKeys.size(); i++) {
if(node.mKeys.get(i).compareTo(keyDataPair) >= 0){
break;
}
}
if(node.mPointers.get(i).mKeys.size() == 2*mMinDegree - 1){
node.split(i);
if(node.mKeys.get(i).compareTo(keyDataPair) < 0)
i++;
}
insertNotFull(node.mPointers.get(i), keyDataPair);
}
}
private class BTreeNode{
private boolean mLeaf;
private List<KeyDataPair> mKeys;
private List<BTreeNode> mPointers;
public BTreeNode(){
mLeaf = true;
mKeys = new LinkedList<>();
mPointers = new LinkedList<>();
}
public void split(int ith){
BTreeNode rightNode = new BTreeNode();
BTreeNode leftNode = this.mPointers.get(ith);
rightNode.mLeaf = leftNode.mLeaf;
//moves all the keys that are the right side of ith to
//the newly created rightNode.
for (int i = 0; i != mMinDegree-1; i++) {
rightNode.mKeys.add(leftNode.mKeys.get(i+mMinDegree));
}
if (!leftNode.mLeaf){
for (int i = 0; i != mMinDegree; i++) {
rightNode.mPointers.add(leftNode.mPointers.get(i+mMinDegree));
}
}
mPointers.add(ith+1, rightNode);
mKeys.add(ith, leftNode.mKeys.get(mMinDegree-1));
for (int i = leftNode.mKeys.size(); i > mMinDegree-1; i--) {
leftNode.mKeys.remove(i-1);
}
for (int i = leftNode.mPointers.size(); i > mMinDegree; i--) {
leftNode.mPointers.remove(i-1);
}
}
}
private class KeyDataPair implements Comparable<KeyDataPair>{
private T mKey;
private U mData;
public KeyDataPair(T key, U value){
mKey = key;
mData = value;
}
@Override
public int compareTo(KeyDataPair o) {
return mKey.compareTo(o.mKey);
}
public int compareTo(T key) {
return mKey.compareTo(key);
}
}
}
| Fixed the search so it will find the correct value every time
| src/uk/ac/cam/josi2/DataStructures/BTree.java | Fixed the search so it will find the correct value every time |
|
Java | mit | 7223b9c093f48ed68e11728cbe477b29decfb1ce | 0 | iwhys/to-animator | package com.iwhys.library.animator;
import android.animation.TimeInterpolator;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.util.ArrayMap;
import android.support.v4.util.Pools;
import android.view.animation.LinearInterpolator;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Author: iwhys
* Email: [email protected]
* Time: 6/28/16 12:36
* Description:
*/
public class AnimatorHolder {
/**
* the max size of every object pool
*/
private static final int MAX_POOL_SIZE = 10;
/**
* the object pools
*/
private final static ArrayMap<Class, Pools.SynchronizedPool<AnimatorHolder>> sPoolMap = new ArrayMap<>();
/**
* The container of the running items
*/
private final ArrayList<AnimatorItem> mRunningList = new ArrayList<>();
/**
* The Container of the recycled items
*/
private final Set<AnimatorItem> mRecyclerSet = Collections.newSetFromMap(new WeakHashMap<AnimatorItem, Boolean>());
/**
* The item' type
*/
private final Class<? extends AnimatorItem> mItemClass;
/**
* The paint
*/
private final Paint mPaint = new Paint();
/**
* The width
*/
private int mWidth;
/**
* The height
*/
private int mHeight;
/**
* Can item be cached
*/
private boolean mCacheItem = true;
/**
* If the speed value is zero and this value is true,
* when the only item finished, it will continue run until the total time is over.
*/
private boolean mFillAfter;
/**
* The total duration of the animator
*/
private long mTotalDuration = -1;
/**
* The default interval for add a new item
* Note: If {@link #needNewItem(long, long, long, long)} be override, the speed is invalidate
*/
private long mSpeed = 300;
/**
* The animator listener
*/
private AnimatorListener mListener;
/**
* The origin rect
*/
private final Rect mOriginRect = new Rect();
/**
* The time when the animator started.
*/
private long mStartTime;
/**
* The delayed duration before the animator start.
*/
private long mStartDelayed;
/**
* The time when the last new item has been added
*/
private long mLastNewItemTime;
/**
* Finish flag
*/
private boolean mFinished = false;
/**
* Cancel flag
*/
private boolean mCanceled = false;
/**
* Has fill after
*/
private boolean mHasFillAfter = false;
/**
* The interface Animator listener.
*/
public static abstract class AnimatorListener {
/**
* On start.
*/
public void onStart(){}
/**
* On finished.
*/
public void onFinished(){}
/**
* On canceled.
*/
public void onCanceled(){}
/**
* On fill after
*/
public void onFillAfter(){}
}
/**
* The constructor
* @param itemClass item class
*/
private AnimatorHolder(Class<? extends AnimatorItem> itemClass){
mItemClass = itemClass;
initPaint();
}
/**
* Retriever an instance from the pool
*
* @param itemClass item class
* @return animator holder
*/
public static AnimatorHolder obtain(Class<? extends AnimatorItem> itemClass){
Pools.SynchronizedPool<AnimatorHolder> pool = sPoolMap.get(itemClass);
if (pool == null){
pool = new Pools.SynchronizedPool<>(MAX_POOL_SIZE);
sPoolMap.put(itemClass, pool);
}
AnimatorHolder holder = pool.acquire();
if (holder != null && holder.mItemClass.equals(itemClass)){
holder.reset();
return holder;
} else {
return new AnimatorHolder(itemClass);
}
}
/**
* destroy the pools
*/
public static void destroyAll(){
Set<Class> keys = sPoolMap.keySet();
for (Class key : keys) {
Pools.SynchronizedPool<AnimatorHolder> pool = sPoolMap.get(key);
if (pool != null){
AnimatorHolder holder = pool.acquire();
for (; holder != null; holder = pool.acquire()){
holder.destroy();
}
}
}
sPoolMap.clear();
}
/**
* Listener animator holder.
*
* @param listener the listener
* @return the animator holder
*/
public AnimatorHolder listener(AnimatorListener listener){
mListener = listener;
return this;
}
/**
* If the value is true, the only item will run until the total time is over.
* @param fillAfter boolean
* @return the animator holder
*/
public AnimatorHolder fillAfter(boolean fillAfter){
mFillAfter = fillAfter;
return this;
}
/**
* Cache item animator holder.
*
* @param cacheItem the cache item
* @return the animator holder
*/
public AnimatorHolder cacheItem(boolean cacheItem){
mCacheItem = cacheItem;
return this;
}
/**
* Speed animator holder.
* Note: if you just need one animator item, set the speed value zero, please
*
* @param speed the speed
* @return the animator holder
*/
public AnimatorHolder speed(long speed){
mSpeed = speed;
return this;
}
/**
* The delay duration before the animator start
*
* @param startDelayed delay
* @return the animator holder
*/
public AnimatorHolder startDelayed(long startDelayed){
mStartDelayed = startDelayed;
return this;
}
/**
* Total duration animator holder.
*
* @param totalDuration the total duration
* @return the animator holder
*/
public AnimatorHolder totalDuration(long totalDuration){
mTotalDuration = totalDuration;
return this;
}
/**
* Origin rect animator holder.
*
* @param originRect the origin rect
* @return the animator holder
*/
public AnimatorHolder originRect(Rect originRect){
if (originRect != null) {
mOriginRect.set(originRect);
}
return this;
}
/**
* Internal invoke by the library, perform add new item, and traversal perform item's drawing method
* don't invoke this method at any time
*
* @param canvas canvas
*/
public final void onDraw(Canvas canvas){
/**
* Set animator start
*/
setAnimatorStart();
/**
* Handle animator delay
*/
if (animatorDelay()) return;
/**
* Handle animator canceled
*/
if (animatorCanceled()) return;
/**
* Add a new item
*/
if (needNewItem(mStartTime, mLastNewItemTime, mTotalDuration, mStartDelayed)){
addNewItem();
}
/**
* Handle animator finished
*/
if (animatorFinished()) return;
/**
* Traversal perform item's drawing method
*/
performDraw(canvas);
}
/**
* Cancel the animator, only for the kind of itemClass
*/
public void cancel(){
mCanceled = true;
}
/**
* Has the animator been canceled
*
* @return result boolean
*/
public boolean isCanceled() {
return mCanceled;
}
/**
* Has the animator been finished
*
* @return result boolean
*/
public boolean isFinished(){
return mFinished;
}
/**
* Set size
*
* @param w the w
* @param h the h
*/
public void setSize(int w, int h){
mWidth = w;
mHeight = h;
}
/**
* Traversal perform item's drawing method,and remove the item finished
* @param canvas the canvas
*/
private void performDraw(Canvas canvas){
final ArrayList<AnimatorItem> runningListCopy = (ArrayList<AnimatorItem>) mRunningList.clone();
for (AnimatorItem item : runningListCopy) {
if (item.isFinished()) {
if (mSpeed ==0 && mFillAfter){
if (mListener != null && !mHasFillAfter){
mHasFillAfter = true;
mListener.onFillAfter();
}
item.onDraw(canvas, mPaint);
} else {
mRunningList.remove(item);
if (mCacheItem){
mRecyclerSet.add(item);
}
}
} else {
item.onDraw(canvas, mPaint);
}
}
}
/**
* Handle animator start
*/
private void setAnimatorStart(){
if (mStartTime == 0){
mStartTime = System.currentTimeMillis();
if (mListener != null){
mListener.onStart();
}
}
}
/**
* Handle animator delay
* @return result
*/
private boolean animatorDelay(){
return System.currentTimeMillis() - mStartTime < mStartDelayed;
}
/**
* Handle animator has been canceled
* @return result
*/
private boolean animatorCanceled(){
if (mCanceled){
if (mListener != null){
mListener.onCanceled();
}
recycle();
return true;
}
return false;
}
/**
* Handle animator finished
* @return result
*/
private boolean animatorFinished(){
if (!mFinished && mRunningList.isEmpty()){
mFinished = true;
if (mListener != null){
mListener.onFinished();
}
recycle();
return true;
}
return false;
}
/**
* Reset the key properties to reuse
*/
public void reset(){
mStartTime = 0;
mLastNewItemTime = 0;
mListener = null;
mFinished = false;
mCanceled = false;
}
/**
* Put current object into the pool
*/
public void recycle(){
Pools.SynchronizedPool<AnimatorHolder> pool = sPoolMap.get(mItemClass);
pool.release(this);
}
/**
* Destroy all items
*/
private void destroy(){
cancel();
for (AnimatorItem animatorItem : mRunningList) {
animatorItem.onDestroy();
}
mRunningList.clear();
for (AnimatorItem animatorItem : mRecyclerSet) {
animatorItem.onDestroy();
}
mRecyclerSet.clear();
}
/**
* Add a new item
*/
private void addNewItem(){
AnimatorItem item = obtainItem();
if (item == null) {
return;
}
long now = System.currentTimeMillis();
item.mStartTime = now;
item.mOriginRect.set(mOriginRect);
item.mWidth = mWidth;
item.mHeight = mHeight;
item.mPosition = mRunningList.size();
item.onAttached();
mRunningList.add(item);
mLastNewItemTime = now;
onNewItemAttached(item);
}
/**
* Retriever an animator item
* @return entity of animator item
*/
private AnimatorItem obtainItem(){
AnimatorItem item = null;
if (mCacheItem){
item = itemFromRecycler();
}
if (item == null){
item = createNewItem();
}
return item;
}
/**
* Retriever an item from the recycler
*
* @return entity
*/
private AnimatorItem itemFromRecycler() {
if (!mRecyclerSet.isEmpty()) {
Iterator<AnimatorItem> itemIterator = mRecyclerSet.iterator();
if (itemIterator.hasNext()){
AnimatorItem item = itemIterator.next();
if (item.isFinished()) {
itemIterator.remove();
return item;
}
}
}
return null;
}
/**
* Initialize the paint
*/
private void initPaint(){
mPaint.setAntiAlias(true);
mPaint.setDither(true);
}
/**
* Create a new item
* the default implement can be override
*
* @return animator item
*/
protected AnimatorItem createNewItem(){
try {
Constructor constructor = mItemClass.getDeclaredConstructor();
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return (AnimatorItem) constructor.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* This method is invoked when the new item has been created
* override to set some properties of the item
*
* @param item the new item
*/
protected void onNewItemAttached(AnimatorItem item){}
/**
* Need to add a new item
* can be override by the subclass
*
* @param startTime the start time
* @param lastNewItemTime the last new item time
* @param totalDuration the total duration
* @param startDelayed the delay duration before start
* @return boolean
*/
protected boolean needNewItem(long startTime, long lastNewItemTime, long totalDuration, long startDelayed){
/**
* for the case only need one item
*/
if (mSpeed == 0){
return lastNewItemTime == 0;
}
long now = System.currentTimeMillis();
boolean speedResult = now - lastNewItemTime >= mSpeed;
boolean otherResult = true;
if (totalDuration >= 0){
if (!mRunningList.isEmpty()){
AnimatorItem lastItem = mRunningList.get(mRunningList.size() - 1);
otherResult = startTime + totalDuration + startDelayed - lastItem.mStartTime > lastItem.mDuration;
} else {
/**
* For the case that the animator is finished, and the running list is empty
*/
otherResult = now - startTime - startDelayed < totalDuration;
}
}
return speedResult && otherResult;
}
/**
* the base class of single animator item
*/
public static abstract class AnimatorItem {
protected final static TimeInterpolator sLinearInterpolator = new LinearInterpolator();
/**
* The M origin rect.
*/
protected final Rect mOriginRect = new Rect();
/**
* The M current rect.
*/
protected final RectF mCurrentRect = new RectF();
/**
* The M position.
*/
protected int mPosition;
/**
* The M width.
*/
protected int mWidth;
/**
* The M height.
*/
protected int mHeight;
/**
* The animator's start time
*/
private long mStartTime;
/**
* The animator's duration
*/
private long mDuration = 1000;
/**
* The animator's time interpolator
*/
private TimeInterpolator mInterpolator = sLinearInterpolator;
/**
* Instantiates a new Animator item.
*/
public AnimatorItem(){
}
/**
* Sets duration.
*
* @param duration the duration
*/
public void setDuration(long duration) {
mDuration = duration;
}
/**
* Sets interpolator.
*
* @param interpolator the interpolator
*/
public void setInterpolator(TimeInterpolator interpolator) {
if (interpolator != null) {
mInterpolator = interpolator;
}
}
/**
* get the item's current rect
*
* @return {@link RectF}
*/
public RectF getCurrentRect() {
return mCurrentRect;
}
/**
* is the animator finished
*
* @return result boolean
*/
public boolean isFinished() {
return getInputValue() >= 1;
}
/**
* get the progress value
*
* @return the progress
*/
protected float getProgress() {
float input = getInputValue();
return mInterpolator.getInterpolation(input);
}
/**
* get the input value
*
* @return valid value[0, 1]
*/
protected float getInputValue() {
float value = (System.currentTimeMillis() - mStartTime) * 1.f / mDuration;
return Math.min(1.f, value);
}
/**
* the item from attach to the running container
*/
protected void onAttached() {
}
/**
* perform the real drawing task
*
* @param canvas canvas
* @param paint paint
*/
protected abstract void onDraw(Canvas canvas, Paint paint);
/**
* release all resources
*/
protected void onDestroy(){}
/**
* Random float.
*
* @param max the max
* @return the float
*/
public static float random(float max){
return random(max, 0);
}
/**
* Random float.
*
* @param max the max
* @param min the min
* @return the float
*/
public static float random(float max, float min){
return (float) (Math.random() * (max - min) + min);
}
}
}
| library/src/main/java/com/iwhys/library/animator/AnimatorHolder.java | package com.iwhys.library.animator;
import android.animation.TimeInterpolator;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.util.ArrayMap;
import android.support.v4.util.Pools;
import android.view.animation.LinearInterpolator;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Author: iwhys
* Email: [email protected]
* Time: 6/28/16 12:36
* Description:
*/
public class AnimatorHolder {
/**
* the max size of every object pool
*/
private static final int MAX_POOL_SIZE = 10;
/**
* the object pools
*/
private final static ArrayMap<Class, Pools.SynchronizedPool<AnimatorHolder>> sPoolMap = new ArrayMap<>();
/**
* The container of the running items
*/
private final ArrayList<AnimatorItem> mRunningList = new ArrayList<>();
/**
* The Container of the recycled items
*/
private final Set<AnimatorItem> mRecyclerSet = Collections.newSetFromMap(new WeakHashMap<AnimatorItem, Boolean>());
/**
* The item' type
*/
private final Class<? extends AnimatorItem> mItemClass;
/**
* The paint
*/
private final Paint mPaint = new Paint();
/**
* The width
*/
private int mWidth;
/**
* The height
*/
private int mHeight;
/**
* Can item be cached
*/
private boolean mCacheItem = true;
/**
* If the speed value is zero and this value is true,
* when the only item finished, it will continue run until the total time is over.
*/
private boolean mFillAfter;
/**
* The total duration of the animator
*/
private long mTotalDuration = -1;
/**
* The default interval for add a new item
* Note: If {@link #needNewItem(long, long, long, long)} be override, the speed is invalidate
*/
private long mSpeed = 300;
/**
* The animator listener
*/
private AnimatorListener mListener;
/**
* The origin rect
*/
private final Rect mOriginRect = new Rect();
/**
* The time when the animator started.
*/
private long mStartTime;
/**
* The delayed duration before the animator start.
*/
private long mStartDelayed;
/**
* The time when the last new item has been added
*/
private long mLastNewItemTime;
/**
* Finish flag
*/
private boolean mFinished = false;
/**
* Cancel flag
*/
private boolean mCanceled = false;
/**
* Has fill after
*/
private boolean mHasFillAfter = false;
/**
* The interface Animator listener.
*/
public static abstract class AnimatorListener {
/**
* On start.
*/
public void onStart(){}
/**
* On finished.
*/
public void onFinished(){}
/**
* On canceled.
*/
public void onCanceled(){}
/**
* On fill after
*/
public void onFillAfter(){}
}
/**
* The constructor
* @param itemClass item class
*/
private AnimatorHolder(Class<? extends AnimatorItem> itemClass){
mItemClass = itemClass;
initPaint();
}
/**
* Retriever an instance from the pool
*
* @param itemClass item class
* @return animator holder
*/
public static AnimatorHolder obtain(Class<? extends AnimatorItem> itemClass){
Pools.SynchronizedPool<AnimatorHolder> pool = sPoolMap.get(itemClass);
if (pool == null){
pool = new Pools.SynchronizedPool<>(MAX_POOL_SIZE);
sPoolMap.put(itemClass, pool);
}
AnimatorHolder holder = pool.acquire();
if (holder != null && holder.mItemClass.equals(itemClass)){
holder.reset();
return holder;
} else {
return new AnimatorHolder(itemClass);
}
}
/**
* destroy the pools
*/
public static void destroyAll(){
Set<Class> keys = sPoolMap.keySet();
for (Class key : keys) {
Pools.SynchronizedPool<AnimatorHolder> pool = sPoolMap.get(key);
if (pool != null){
while (pool.acquire() != null){
AnimatorHolder holder = pool.acquire();
holder.destroy();
}
}
}
sPoolMap.clear();
}
/**
* Listener animator holder.
*
* @param listener the listener
* @return the animator holder
*/
public AnimatorHolder listener(AnimatorListener listener){
mListener = listener;
return this;
}
/**
* If the value is true, the only item will run until the total time is over.
* @param fillAfter boolean
* @return the animator holder
*/
public AnimatorHolder fillAfter(boolean fillAfter){
mFillAfter = fillAfter;
return this;
}
/**
* Cache item animator holder.
*
* @param cacheItem the cache item
* @return the animator holder
*/
public AnimatorHolder cacheItem(boolean cacheItem){
mCacheItem = cacheItem;
return this;
}
/**
* Speed animator holder.
* Note: if you just need one animator item, set the speed value zero, please
*
* @param speed the speed
* @return the animator holder
*/
public AnimatorHolder speed(long speed){
mSpeed = speed;
return this;
}
/**
* The delay duration before the animator start
*
* @param startDelayed delay
* @return the animator holder
*/
public AnimatorHolder startDelayed(long startDelayed){
mStartDelayed = startDelayed;
return this;
}
/**
* Total duration animator holder.
*
* @param totalDuration the total duration
* @return the animator holder
*/
public AnimatorHolder totalDuration(long totalDuration){
mTotalDuration = totalDuration;
return this;
}
/**
* Origin rect animator holder.
*
* @param originRect the origin rect
* @return the animator holder
*/
public AnimatorHolder originRect(Rect originRect){
if (originRect != null) {
mOriginRect.set(originRect);
}
return this;
}
/**
* Internal invoke by the library, perform add new item, and traversal perform item's drawing method
* don't invoke this method at any time
*
* @param canvas canvas
*/
public final void onDraw(Canvas canvas){
/**
* Set animator start
*/
setAnimatorStart();
/**
* Handle animator delay
*/
if (animatorDelay()) return;
/**
* Handle animator canceled
*/
if (animatorCanceled()) return;
/**
* Add a new item
*/
if (needNewItem(mStartTime, mLastNewItemTime, mTotalDuration, mStartDelayed)){
addNewItem();
}
/**
* Handle animator finished
*/
if (animatorFinished()) return;
/**
* Traversal perform item's drawing method
*/
performDraw(canvas);
}
/**
* Cancel the animator, only for the kind of itemClass
*/
public void cancel(){
mCanceled = true;
}
/**
* Has the animator been canceled
*
* @return result boolean
*/
public boolean isCanceled() {
return mCanceled;
}
/**
* Has the animator been finished
*
* @return result boolean
*/
public boolean isFinished(){
return mFinished;
}
/**
* Set size
*
* @param w the w
* @param h the h
*/
public void setSize(int w, int h){
mWidth = w;
mHeight = h;
}
/**
* Traversal perform item's drawing method,and remove the item finished
* @param canvas the canvas
*/
private void performDraw(Canvas canvas){
final ArrayList<AnimatorItem> runningListCopy = (ArrayList<AnimatorItem>) mRunningList.clone();
for (AnimatorItem item : runningListCopy) {
if (item.isFinished()) {
if (mSpeed ==0 && mFillAfter){
if (mListener != null && !mHasFillAfter){
mHasFillAfter = true;
mListener.onFillAfter();
}
item.onDraw(canvas, mPaint);
} else {
mRunningList.remove(item);
if (mCacheItem){
mRecyclerSet.add(item);
}
}
} else {
item.onDraw(canvas, mPaint);
}
}
}
/**
* Handle animator start
*/
private void setAnimatorStart(){
if (mStartTime == 0){
mStartTime = System.currentTimeMillis();
if (mListener != null){
mListener.onStart();
}
}
}
/**
* Handle animator delay
* @return result
*/
private boolean animatorDelay(){
return System.currentTimeMillis() - mStartTime < mStartDelayed;
}
/**
* Handle animator has been canceled
* @return result
*/
private boolean animatorCanceled(){
if (mCanceled){
if (mListener != null){
mListener.onCanceled();
}
recycle();
return true;
}
return false;
}
/**
* Handle animator finished
* @return result
*/
private boolean animatorFinished(){
if (!mFinished && mRunningList.isEmpty()){
mFinished = true;
if (mListener != null){
mListener.onFinished();
}
recycle();
return true;
}
return false;
}
/**
* Reset the key properties to reuse
*/
public void reset(){
mStartTime = 0;
mLastNewItemTime = 0;
mListener = null;
mFinished = false;
mCanceled = false;
}
/**
* Put current object into the pool
*/
public void recycle(){
Pools.SynchronizedPool<AnimatorHolder> pool = sPoolMap.get(mItemClass);
pool.release(this);
}
/**
* Destroy all items
*/
private void destroy(){
cancel();
for (AnimatorItem animatorItem : mRunningList) {
animatorItem.onDestroy();
}
mRunningList.clear();
for (AnimatorItem animatorItem : mRecyclerSet) {
animatorItem.onDestroy();
}
mRecyclerSet.clear();
}
/**
* Add a new item
*/
private void addNewItem(){
AnimatorItem item = obtainItem();
if (item == null) {
return;
}
long now = System.currentTimeMillis();
item.mStartTime = now;
item.mOriginRect.set(mOriginRect);
item.mWidth = mWidth;
item.mHeight = mHeight;
item.mPosition = mRunningList.size();
item.onAttached();
mRunningList.add(item);
mLastNewItemTime = now;
onNewItemAttached(item);
}
/**
* Retriever an animator item
* @return entity of animator item
*/
private AnimatorItem obtainItem(){
AnimatorItem item = null;
if (mCacheItem){
item = itemFromRecycler();
}
if (item == null){
item = createNewItem();
}
return item;
}
/**
* Retriever an item from the recycler
*
* @return entity
*/
private AnimatorItem itemFromRecycler() {
if (!mRecyclerSet.isEmpty()) {
Iterator<AnimatorItem> itemIterator = mRecyclerSet.iterator();
if (itemIterator.hasNext()){
AnimatorItem item = itemIterator.next();
if (item.isFinished()) {
itemIterator.remove();
return item;
}
}
}
return null;
}
/**
* Initialize the paint
*/
private void initPaint(){
mPaint.setAntiAlias(true);
mPaint.setDither(true);
}
/**
* Create a new item
* the default implement can be override
*
* @return animator item
*/
protected AnimatorItem createNewItem(){
try {
Constructor constructor = mItemClass.getDeclaredConstructor();
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return (AnimatorItem) constructor.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* This method is invoked when the new item has been created
* override to set some properties of the item
*
* @param item the new item
*/
protected void onNewItemAttached(AnimatorItem item){}
/**
* Need to add a new item
* can be override by the subclass
*
* @param startTime the start time
* @param lastNewItemTime the last new item time
* @param totalDuration the total duration
* @param startDelayed the delay duration before start
* @return boolean
*/
protected boolean needNewItem(long startTime, long lastNewItemTime, long totalDuration, long startDelayed){
/**
* for the case only need one item
*/
if (mSpeed == 0){
return lastNewItemTime == 0;
}
long now = System.currentTimeMillis();
boolean speedResult = now - lastNewItemTime >= mSpeed;
boolean otherResult = true;
if (totalDuration >= 0){
if (!mRunningList.isEmpty()){
AnimatorItem lastItem = mRunningList.get(mRunningList.size() - 1);
otherResult = startTime + totalDuration + startDelayed - lastItem.mStartTime > lastItem.mDuration;
} else {
/**
* For the case that the animator is finished, and the running list is empty
*/
otherResult = now - startTime - startDelayed < totalDuration;
}
}
return speedResult && otherResult;
}
/**
* the base class of single animator item
*/
public static abstract class AnimatorItem {
protected final static TimeInterpolator sLinearInterpolator = new LinearInterpolator();
/**
* The M origin rect.
*/
protected final Rect mOriginRect = new Rect();
/**
* The M current rect.
*/
protected final RectF mCurrentRect = new RectF();
/**
* The M position.
*/
protected int mPosition;
/**
* The M width.
*/
protected int mWidth;
/**
* The M height.
*/
protected int mHeight;
/**
* The animator's start time
*/
private long mStartTime;
/**
* The animator's duration
*/
private long mDuration = 1000;
/**
* The animator's time interpolator
*/
private TimeInterpolator mInterpolator = sLinearInterpolator;
/**
* Instantiates a new Animator item.
*/
public AnimatorItem(){
}
/**
* Sets duration.
*
* @param duration the duration
*/
public void setDuration(long duration) {
mDuration = duration;
}
/**
* Sets interpolator.
*
* @param interpolator the interpolator
*/
public void setInterpolator(TimeInterpolator interpolator) {
if (interpolator != null) {
mInterpolator = interpolator;
}
}
/**
* get the item's current rect
*
* @return {@link RectF}
*/
public RectF getCurrentRect() {
return mCurrentRect;
}
/**
* is the animator finished
*
* @return result boolean
*/
public boolean isFinished() {
return getInputValue() >= 1;
}
/**
* get the progress value
*
* @return the progress
*/
protected float getProgress() {
float input = getInputValue();
return mInterpolator.getInterpolation(input);
}
/**
* get the input value
*
* @return valid value[0, 1]
*/
protected float getInputValue() {
float value = (System.currentTimeMillis() - mStartTime) * 1.f / mDuration;
return Math.min(1.f, value);
}
/**
* the item from attach to the running container
*/
protected void onAttached() {
}
/**
* perform the real drawing task
*
* @param canvas canvas
* @param paint paint
*/
protected abstract void onDraw(Canvas canvas, Paint paint);
/**
* release all resources
*/
protected void onDestroy(){}
/**
* Random float.
*
* @param max the max
* @return the float
*/
public static float random(float max){
return random(max, 0);
}
/**
* Random float.
*
* @param max the max
* @param min the min
* @return the float
*/
public static float random(float max, float min){
return (float) (Math.random() * (max - min) + min);
}
}
}
| fix exception on destroy holder
| library/src/main/java/com/iwhys/library/animator/AnimatorHolder.java | fix exception on destroy holder |
|
Java | mit | e3eb85a37b1aeacacd229a6d11f1f17da45be9c3 | 0 | tanguyantoine/react-native-music-control,tanguyantoine/react-native-music-control,tanguyantoine/react-native-music-control,tanguyantoine/react-native-music-control | package com.tanguyantoine.react;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.support.v4.app.NotificationCompat;
import android.view.KeyEvent;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableMap;
import java.util.Map;
import static android.support.v4.app.NotificationCompat.PRIORITY_MIN;
import static com.tanguyantoine.react.MusicControlModule.CHANNEL_ID;
import static com.tanguyantoine.react.MusicControlModule.NOTIFICATION_ID;
public class MusicControlNotification {
protected static final String REMOVE_NOTIFICATION = "music_control_remove_notification";
protected static final String MEDIA_BUTTON = "music_control_media_button";
protected static final String PACKAGE_NAME = "music_control_package_name";
private final ReactApplicationContext context;
private final MusicControlModule module;
private int smallIcon;
private int customIcon;
private NotificationCompat.Action play, pause, stop, next, previous, skipForward, skipBackward;
public MusicControlNotification(MusicControlModule module, ReactApplicationContext context) {
this.context = context;
this.module = module;
Resources r = context.getResources();
String packageName = context.getPackageName();
// Optional custom icon with fallback to the play icon
smallIcon = r.getIdentifier("music_control_icon", "drawable", packageName);
if (smallIcon == 0) smallIcon = r.getIdentifier("play", "drawable", packageName);
}
public synchronized void setCustomNotificationIcon(String resourceName) {
if (resourceName == null) {
customIcon = 0;
return;
}
Resources r = context.getResources();
String packageName = context.getPackageName();
customIcon = r.getIdentifier(resourceName, "drawable", packageName);
}
public synchronized void updateActions(long mask, Map<String, Integer> options) {
play = createAction("play", "Play", mask, PlaybackStateCompat.ACTION_PLAY, play);
pause = createAction("pause", "Pause", mask, PlaybackStateCompat.ACTION_PAUSE, pause);
stop = createAction("stop", "Stop", mask, PlaybackStateCompat.ACTION_STOP, stop);
next = createAction("next", "Next", mask, PlaybackStateCompat.ACTION_SKIP_TO_NEXT, next);
previous = createAction("previous", "Previous", mask, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS, previous);
if (options != null && options.containsKey("skipForward") && (options.get("skipForward") == 10 || options.get("skipForward") == 5 || options.get("skipForward") == 30)) {
skipForward = createAction("skip_forward_" + options.get("skipForward").toString(), "Skip Forward", mask, PlaybackStateCompat.ACTION_FAST_FORWARD, skipForward);
} else {
skipForward = createAction("skip_forward_10", "Skip Forward", mask, PlaybackStateCompat.ACTION_FAST_FORWARD, skipForward);
}
if (options != null && options.containsKey("skipBackward") && (options.get("skipBackward") == 10 || options.get("skipBackward") == 5 || options.get("skipBackward") == 30)) {
skipBackward = createAction("skip_backward_" + options.get("skipBackward").toString(), "Skip Backward", mask, PlaybackStateCompat.ACTION_REWIND, skipBackward);
} else {
skipBackward = createAction("skip_backward_10", "Skip Backward", mask, PlaybackStateCompat.ACTION_REWIND, skipBackward);
}
}
public Notification prepareNotification(NotificationCompat.Builder builder, boolean isPlaying) {
// Add the buttons
builder.mActions.clear();
if (previous != null) builder.addAction(previous);
if (skipBackward != null) builder.addAction(skipBackward);
if (play != null && !isPlaying) builder.addAction(play);
if (pause != null && isPlaying) builder.addAction(pause);
if (stop != null) builder.addAction(stop);
if (next != null) builder.addAction(next);
if (skipForward != null) builder.addAction(skipForward);
// Set whether notification can be closed based on closeNotification control (default PAUSED)
if (module.notificationClose == MusicControlModule.NotificationClose.ALWAYS) {
builder.setOngoing(false);
} else if (module.notificationClose == MusicControlModule.NotificationClose.PAUSED) {
builder.setOngoing(isPlaying);
} else { // NotificationClose.NEVER
builder.setOngoing(true);
}
builder.setSmallIcon(customIcon != 0 ? customIcon : smallIcon);
// Open the app when the notification is clicked
String packageName = context.getPackageName();
Intent openApp = context.getPackageManager().getLaunchIntentForPackage(packageName);
builder.setContentIntent(PendingIntent.getActivity(context, 0, openApp, 0));
// Remove notification
Intent remove = new Intent(REMOVE_NOTIFICATION);
remove.putExtra(PACKAGE_NAME, context.getApplicationInfo().packageName);
builder.setDeleteIntent(PendingIntent.getBroadcast(context, 0, remove, PendingIntent.FLAG_UPDATE_CURRENT));
return builder.build();
}
public synchronized void show(NotificationCompat.Builder builder, boolean isPlaying) {
NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, prepareNotification(builder, isPlaying));
}
public void hide() {
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent myIntent = new Intent(context, MusicControlNotification.NotificationService.class);
context.stopService(myIntent);
}
}
/**
* Code taken from newer version of the support library located in PlaybackStateCompat.toKeyCode
* Replace this to PlaybackStateCompat.toKeyCode when React Native updates the support library
*/
private int toKeyCode(long action) {
if (action == PlaybackStateCompat.ACTION_PLAY) {
return KeyEvent.KEYCODE_MEDIA_PLAY;
} else if (action == PlaybackStateCompat.ACTION_PAUSE) {
return KeyEvent.KEYCODE_MEDIA_PAUSE;
} else if (action == PlaybackStateCompat.ACTION_SKIP_TO_NEXT) {
return KeyEvent.KEYCODE_MEDIA_NEXT;
} else if (action == PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) {
return KeyEvent.KEYCODE_MEDIA_PREVIOUS;
} else if (action == PlaybackStateCompat.ACTION_STOP) {
return KeyEvent.KEYCODE_MEDIA_STOP;
} else if (action == PlaybackStateCompat.ACTION_FAST_FORWARD) {
return KeyEvent.KEYCODE_MEDIA_FAST_FORWARD;
} else if (action == PlaybackStateCompat.ACTION_REWIND) {
return KeyEvent.KEYCODE_MEDIA_REWIND;
} else if (action == PlaybackStateCompat.ACTION_PLAY_PAUSE) {
return KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
}
return KeyEvent.KEYCODE_UNKNOWN;
}
private NotificationCompat.Action createAction(String iconName, String title, long mask, long action, NotificationCompat.Action oldAction) {
if ((mask & action) == 0) return null; // When this action is not enabled, return null
if (oldAction != null)
return oldAction; // If this action was already created, we won't create another instance
// Finds the icon with the given name
Resources r = context.getResources();
String packageName = context.getPackageName();
int icon = r.getIdentifier(iconName, "drawable", packageName);
// Creates the intent based on the action
int keyCode = toKeyCode(action);
Intent intent = new Intent(MEDIA_BUTTON);
intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
intent.putExtra(PACKAGE_NAME, packageName);
PendingIntent i = PendingIntent.getBroadcast(context, keyCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Action(icon, title, i);
}
public static class NotificationService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
private boolean isRunning;
private Notification notification;
@Override
public void onCreate() {
super.onCreate();
if (MusicControlModule.INSTANCE != null && MusicControlModule.INSTANCE.notification != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notification = MusicControlModule.INSTANCE.notification.prepareNotification(MusicControlModule.INSTANCE.nb, false);
startForeground(NOTIFICATION_ID, notification);
isRunning = true;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (intent.getAction() != null && intent.getAction().equals("StopService") && notification != null && isRunning) {
stopForeground(true);
isRunning = false;
stopSelf();
}
}
return START_NOT_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
isRunning = false;
// Destroy the notification and sessions when the task is removed (closed, killed, etc)
if (MusicControlModule.INSTANCE != null) {
MusicControlModule.INSTANCE.destroy();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true);
}
stopSelf(); // Stop the service as we won't need it anymore
}
@Override
public void onDestroy() {
isRunning = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true);
}
}
}
}
| android/src/main/java/com/tanguyantoine/react/MusicControlNotification.java | package com.tanguyantoine.react;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.support.v4.app.NotificationCompat;
import android.view.KeyEvent;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableMap;
import java.util.Map;
import static android.support.v4.app.NotificationCompat.PRIORITY_MIN;
import static com.tanguyantoine.react.MusicControlModule.CHANNEL_ID;
import static com.tanguyantoine.react.MusicControlModule.NOTIFICATION_ID;
public class MusicControlNotification {
protected static final String REMOVE_NOTIFICATION = "music_control_remove_notification";
protected static final String MEDIA_BUTTON = "music_control_media_button";
protected static final String PACKAGE_NAME = "music_control_package_name";
private final ReactApplicationContext context;
private final MusicControlModule module;
private int smallIcon;
private int customIcon;
private NotificationCompat.Action play, pause, stop, next, previous, skipForward, skipBackward;
public MusicControlNotification(MusicControlModule module, ReactApplicationContext context) {
this.context = context;
this.module = module;
Resources r = context.getResources();
String packageName = context.getPackageName();
// Optional custom icon with fallback to the play icon
smallIcon = r.getIdentifier("music_control_icon", "drawable", packageName);
if (smallIcon == 0) smallIcon = r.getIdentifier("play", "drawable", packageName);
}
public synchronized void setCustomNotificationIcon(String resourceName) {
if (resourceName == null) {
customIcon = 0;
return;
}
Resources r = context.getResources();
String packageName = context.getPackageName();
customIcon = r.getIdentifier(resourceName, "drawable", packageName);
}
public synchronized void updateActions(long mask, Map<String, Integer> options) {
play = createAction("play", "Play", mask, PlaybackStateCompat.ACTION_PLAY, play);
pause = createAction("pause", "Pause", mask, PlaybackStateCompat.ACTION_PAUSE, pause);
stop = createAction("stop", "Stop", mask, PlaybackStateCompat.ACTION_STOP, stop);
next = createAction("next", "Next", mask, PlaybackStateCompat.ACTION_SKIP_TO_NEXT, next);
previous = createAction("previous", "Previous", mask, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS, previous);
if (options != null && options.containsKey("skipForward") && (options.get("skipForward") == 10 || options.get("skipForward") == 5 || options.get("skipForward") == 30)) {
skipForward = createAction("skip_forward_" + options.get("skipForward").toString(), "Skip Forward", mask, PlaybackStateCompat.ACTION_FAST_FORWARD, skipForward);
} else {
skipForward = createAction("skip_forward_10", "Skip Forward", mask, PlaybackStateCompat.ACTION_FAST_FORWARD, skipForward);
}
if (options != null && options.containsKey("skipBackward") && (options.get("skipBackward") == 10 || options.get("skipBackward") == 5 || options.get("skipBackward") == 30)) {
skipBackward = createAction("skip_backward_" + options.get("skipBackward").toString(), "Skip Backward", mask, PlaybackStateCompat.ACTION_REWIND, skipBackward);
} else {
skipBackward = createAction("skip_backward_10", "Skip Backward", mask, PlaybackStateCompat.ACTION_REWIND, skipBackward);
}
}
public Notification prepareNotification(NotificationCompat.Builder builder, boolean isPlaying) {
// Add the buttons
builder.mActions.clear();
if (previous != null) builder.addAction(previous);
if (skipBackward != null) builder.addAction(skipBackward);
if (play != null && !isPlaying) builder.addAction(play);
if (pause != null && isPlaying) builder.addAction(pause);
if (stop != null) builder.addAction(stop);
if (next != null) builder.addAction(next);
if (skipForward != null) builder.addAction(skipForward);
// Set whether notification can be closed based on closeNotification control (default PAUSED)
if (module.notificationClose == MusicControlModule.NotificationClose.ALWAYS) {
builder.setOngoing(false);
} else if (module.notificationClose == MusicControlModule.NotificationClose.PAUSED) {
builder.setOngoing(isPlaying);
} else { // NotificationClose.NEVER
builder.setOngoing(true);
}
builder.setSmallIcon(customIcon != 0 ? customIcon : smallIcon);
// Open the app when the notification is clicked
String packageName = context.getPackageName();
Intent openApp = context.getPackageManager().getLaunchIntentForPackage(packageName);
builder.setContentIntent(PendingIntent.getActivity(context, 0, openApp, 0));
// Remove notification
Intent remove = new Intent(REMOVE_NOTIFICATION);
remove.putExtra(PACKAGE_NAME, context.getApplicationInfo().packageName);
builder.setDeleteIntent(PendingIntent.getBroadcast(context, 0, remove, PendingIntent.FLAG_UPDATE_CURRENT));
return builder.build();
}
public synchronized void show(NotificationCompat.Builder builder, boolean isPlaying) {
NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, prepareNotification(builder, isPlaying));
}
public void hide() {
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent myIntent = new Intent(context, MusicControlNotification.NotificationService.class);
context.stopService(myIntent);
}
}
/**
* Code taken from newer version of the support library located in PlaybackStateCompat.toKeyCode
* Replace this to PlaybackStateCompat.toKeyCode when React Native updates the support library
*/
private int toKeyCode(long action) {
if (action == PlaybackStateCompat.ACTION_PLAY) {
return KeyEvent.KEYCODE_MEDIA_PLAY;
} else if (action == PlaybackStateCompat.ACTION_PAUSE) {
return KeyEvent.KEYCODE_MEDIA_PAUSE;
} else if (action == PlaybackStateCompat.ACTION_SKIP_TO_NEXT) {
return KeyEvent.KEYCODE_MEDIA_NEXT;
} else if (action == PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) {
return KeyEvent.KEYCODE_MEDIA_PREVIOUS;
} else if (action == PlaybackStateCompat.ACTION_STOP) {
return KeyEvent.KEYCODE_MEDIA_STOP;
} else if (action == PlaybackStateCompat.ACTION_FAST_FORWARD) {
return KeyEvent.KEYCODE_MEDIA_FAST_FORWARD;
} else if (action == PlaybackStateCompat.ACTION_REWIND) {
return KeyEvent.KEYCODE_MEDIA_REWIND;
} else if (action == PlaybackStateCompat.ACTION_PLAY_PAUSE) {
return KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
}
return KeyEvent.KEYCODE_UNKNOWN;
}
private NotificationCompat.Action createAction(String iconName, String title, long mask, long action, NotificationCompat.Action oldAction) {
if ((mask & action) == 0) return null; // When this action is not enabled, return null
if (oldAction != null)
return oldAction; // If this action was already created, we won't create another instance
// Finds the icon with the given name
Resources r = context.getResources();
String packageName = context.getPackageName();
int icon = r.getIdentifier(iconName, "drawable", packageName);
// Creates the intent based on the action
int keyCode = toKeyCode(action);
Intent intent = new Intent(MEDIA_BUTTON);
intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode));
intent.putExtra(PACKAGE_NAME, packageName);
PendingIntent i = PendingIntent.getBroadcast(context, keyCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Action(icon, title, i);
}
public static class NotificationService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
private boolean isRunning;
private Notification notification;
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notification = MusicControlModule.INSTANCE.notification.prepareNotification(MusicControlModule.INSTANCE.nb, false);
startForeground(NOTIFICATION_ID, notification);
isRunning = true;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (intent.getAction() != null && intent.getAction().equals("StopService") && notification != null && isRunning) {
stopForeground(true);
isRunning = false;
stopSelf();
}
}
return START_NOT_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
isRunning = false;
// Destroy the notification and sessions when the task is removed (closed, killed, etc)
if (MusicControlModule.INSTANCE != null) {
MusicControlModule.INSTANCE.destroy();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true);
}
stopSelf(); // Stop the service as we won't need it anymore
}
@Override
public void onDestroy() {
isRunning = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true);
}
}
}
}
| Handled edge case NPE.
| android/src/main/java/com/tanguyantoine/react/MusicControlNotification.java | Handled edge case NPE. |
|
Java | mit | 892df6d08cccfd4247f06404236f38e526c2a0d9 | 0 | magullo/jmxtrans,jmxtrans/jmxtrans,jmxtrans/jmxtrans,jmxtrans/jmxtrans,jmxtrans/jmxtrans,magullo/jmxtrans,jmxtrans/jmxtrans,magullo/jmxtrans,magullo/jmxtrans | /**
* The MIT License
* Copyright © 2010 JmxTrans team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.jmxtrans.model;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.name.Named;
import com.googlecode.jmxtrans.connections.JMXConnection;
import com.googlecode.jmxtrans.connections.JmxConnectionProvider;
import com.sun.tools.attach.VirtualMachine;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.apache.commons.pool.KeyedObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.NotThreadSafe;
import javax.annotation.concurrent.ThreadSafe;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import static com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion.NON_NULL;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.ImmutableSet.copyOf;
import static javax.management.remote.JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES;
import static javax.naming.Context.SECURITY_CREDENTIALS;
import static javax.naming.Context.SECURITY_PRINCIPAL;
import static javax.management.remote.rmi.RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE;
/**
* Represents a jmx server that we want to connect to. This also stores the
* queries that we want to execute against the server.
*
* @author jon
*/
@JsonSerialize(include = NON_NULL)
@JsonPropertyOrder(value = {
"alias",
"local",
"pid",
"host",
"port",
"username",
"password",
"cronExpression",
"numQueryThreads",
"protocolProviderPackages"
})
@Immutable
@ThreadSafe
@EqualsAndHashCode(exclude = {"queries", "pool", "outputWriters", "outputWriterFactories"})
@ToString(of = {"pid", "host", "port", "url", "cronExpression", "numQueryThreads"})
public class Server implements JmxConnectionProvider {
private static final String CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
private static final String FRONT = "service:jmx:rmi:///jndi/rmi://";
private static final String BACK = "/jmxrmi";
private static final int DEFAULT_SOCKET_SO_TIMEOUT_MILLIS = 10000;
private static final Logger logger = LoggerFactory.getLogger(Server.class);
/** Returns id for internal logic */
@Getter private final String id;
/**
* Some writers (GraphiteWriter) use the alias in generation of the unique
* key which references this server.
*/
@Getter private final String alias;
/** Returns the pid of the local process jmxtrans will attach to. */
@Getter private final String pid;
private final String host;
private final String port;
@Getter private final String username;
@Getter private final String password;
/**
* This is some obtuse shit for enabling weblogic support.
* <p/>
* http://download.oracle.com/docs/cd/E13222_01/wls/docs90/jmx/accessWLS.
* html
* <p/>
* You'd set this to: weblogic.management.remote
*/
@Getter private final String protocolProviderPackages;
private final String url;
/**
* Each server can set a cronExpression for the scheduler. If the
* cronExpression is null, then the job is run immediately and once.
* Otherwise, it is added to the scheduler for immediate execution and run
* according to the cronExpression.
*
* @deprecated use runPeriodSeconds instead
*/
@Deprecated
@Getter @Nullable private final String cronExpression;
@Getter @Nullable private final Integer runPeriodSeconds;
/** The number of query threads for this server. */
@Getter private final int numQueryThreads;
/**
* Whether the current local Java process should be used or not (useful for
* polling the embedded JVM when using JmxTrans inside a JVM to poll JMX
* stats and push them remotely)
*/
@Getter private final boolean local;
/**
* Whether the remote JMX server should be requested through SSL connection
*/
@Getter private final boolean ssl;
@Getter private final ImmutableSet<Query> queries;
@Nonnull @Getter private final Iterable<OutputWriter> outputWriters;
@Nonnull private final KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool;
@Nonnull @Getter private final ImmutableList<OutputWriterFactory> outputWriterFactories;
@JsonCreator
public Server(
@JsonProperty("alias") String alias,
@JsonProperty("pid") String pid,
@JsonProperty("host") String host,
@JsonProperty("port") String port,
@JsonProperty("username") String username,
@JsonProperty("password") String password,
@JsonProperty("protocolProviderPackages") String protocolProviderPackages,
@JsonProperty("url") String url,
@JsonProperty("cronExpression") String cronExpression,
@JsonProperty("runPeriodSeconds") Integer runPeriodSeconds,
@JsonProperty("numQueryThreads") Integer numQueryThreads,
@JsonProperty("local") boolean local,
@JsonProperty("ssl") boolean ssl,
@JsonProperty("queries") List<Query> queries,
@JsonProperty("outputWriters") List<OutputWriterFactory> outputWriters,
@JacksonInject @Named("mbeanPool") KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool) {
this(alias, pid, host, port, username, password, protocolProviderPackages, url, cronExpression,
runPeriodSeconds, numQueryThreads, local, ssl, queries, outputWriters, ImmutableList.<OutputWriter>of(),
pool);
}
public Server(
String alias,
String pid,
String host,
String port,
String username,
String password,
String protocolProviderPackages,
String url,
String cronExpression,
Integer runPeriodSeconds,
Integer numQueryThreads,
boolean local,
boolean ssl,
List<Query> queries,
ImmutableList<OutputWriter> outputWriters,
KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool) {
this(alias, pid, host, port, username, password, protocolProviderPackages, url, cronExpression,
runPeriodSeconds, numQueryThreads, local, ssl, queries, ImmutableList.<OutputWriterFactory>of(),
outputWriters, pool);
}
private Server(
String alias,
String pid,
String host,
String port,
String username,
String password,
String protocolProviderPackages,
String url,
String cronExpression,
Integer runPeriodSeconds,
Integer numQueryThreads,
boolean local,
boolean ssl,
List<Query> queries,
List<OutputWriterFactory> outputWriterFactories,
List<OutputWriter> outputWriters,
KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool) {
checkArgument(pid != null || url != null || host != null,
"You must provide the pid or the [url|host and port]");
checkArgument(!(pid != null && (url != null || host != null)),
"You must provide the pid OR the url, not both");
this.alias = alias;
this.pid = pid;
this.port = port;
this.username = username;
this.password = password;
this.protocolProviderPackages = protocolProviderPackages;
this.url = url;
this.cronExpression = cronExpression;
if (!isNullOrEmpty(cronExpression)) {
logger.warn("cronExpression is deprecated, please use runPeriodSeconds instead.");
}
this.runPeriodSeconds = runPeriodSeconds;
this.numQueryThreads = firstNonNull(numQueryThreads, 0);
this.local = local;
this.ssl = ssl;
this.queries = copyOf(queries);
// when connecting in local, we cache the host after retrieving it from the network card
if(pid != null) {
try {
this.host = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
// should work, so just throw a runtime if it doesn't
throw new RuntimeException(e);
}
}
else {
this.host = host;
}
this.pool = checkNotNull(pool);
this.outputWriterFactories = ImmutableList.copyOf(firstNonNull(outputWriterFactories, ImmutableList.<OutputWriterFactory>of()));
this.outputWriters = ImmutableList.copyOf(firstNonNull(outputWriters, ImmutableList.<OutputWriter>of()));
this.id = String.format("%s_%s_%s", host, port, pid);
}
public Iterable<Result> execute(Query query) throws Exception {
JMXConnection jmxConnection = null;
try {
jmxConnection = pool.borrowObject(this);
ImmutableList.Builder<Result> results = ImmutableList.builder();
MBeanServerConnection connection = jmxConnection.getMBeanServerConnection();
for (ObjectName queryName : query.queryNames(connection)) {
results.addAll(query.fetchResults(connection, queryName));
}
return results.build();
} catch (Exception e) {
if (jmxConnection != null) {
pool.invalidateObject(this, jmxConnection);
jmxConnection = null;
}
throw e;
}
finally {
if (jmxConnection != null) {
pool.returnObject(this, jmxConnection);
}
}
}
/**
* Generates the proper username/password environment for JMX connections.
*/
@JsonIgnore
public ImmutableMap<String, ?> getEnvironment() {
if (getProtocolProviderPackages() != null && getProtocolProviderPackages().contains("weblogic")) {
ImmutableMap.Builder<String, String> environment = ImmutableMap.builder();
if ((username != null) && (password != null)) {
environment.put(PROTOCOL_PROVIDER_PACKAGES, getProtocolProviderPackages());
environment.put(SECURITY_PRINCIPAL, username);
environment.put(SECURITY_CREDENTIALS, password);
}
return environment.build();
}
ImmutableMap.Builder<String, Object> environment = ImmutableMap.builder();
if ((username != null) && (password != null)) {
String[] credentials = new String[] {
username,
password
};
environment.put(JMXConnector.CREDENTIALS, credentials);
}
JmxTransRMIClientSocketFactory rmiClientSocketFactory = new JmxTransRMIClientSocketFactory(DEFAULT_SOCKET_SO_TIMEOUT_MILLIS, ssl);
// The following is required when JMX is secured with SSL
// with com.sun.management.jmxremote.ssl=true
// as shown in http://docs.oracle.com/javase/8/docs/technotes/guides/management/agent.html#gdfvq
environment.put(RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, rmiClientSocketFactory);
// The following is required when JNDI Registry is secured with SSL
// with com.sun.management.jmxremote.registry.ssl=true
// This property is defined in com.sun.jndi.rmi.registry.RegistryContext.SOCKET_FACTORY
environment.put("com.sun.jndi.rmi.factory.socket", rmiClientSocketFactory);
return environment.build();
}
/**
* Helper method for connecting to a Server. You need to close the resulting
* connection.
*/
@Override
@JsonIgnore
public JMXConnector getServerConnection() throws IOException {
JMXServiceURL url = getJmxServiceURL();
return JMXConnectorFactory.connect(url, this.getEnvironment());
}
@Override
@JsonIgnore
public MBeanServer getLocalMBeanServer() {
// Getting the platform MBean server is cheap (expect for th first call) no need to cache it.
return ManagementFactory.getPlatformMBeanServer();
}
@JsonIgnore
public String getLabel() {
return firstNonNull(alias, host);
}
public String getHost() {
if (host == null && url == null) {
return null;
}
if (host != null) {
return host;
}
// removed the caching of the extracted host as it is a very minor
// optimization we should probably pre compute it in the builder and
// throw exception at construction if both url and host are set
// we might also be able to use java.net.URI to parse the URL, but I'm
// not familiar enough with JMX URLs to think of the test cases ...
return url.substring(url.lastIndexOf("//") + 2, url.lastIndexOf(':'));
}
public String getAlias() {
if (alias == null) {
return null;
}
return alias;
}
public String getSource() {
if (alias != null) {
return alias;
}
return this.getHost();
}
public String getPort() {
if (port == null && url == null) {
return null;
}
if (this.port != null) {
return port;
}
return extractPortFromUrl(url);
}
private static String extractPortFromUrl(String url) {
String computedPort = url.substring(url.lastIndexOf(':') + 1);
if (computedPort.contains("/")) {
computedPort = computedPort.substring(0, computedPort.indexOf('/'));
}
return computedPort;
}
/**
* The jmx url to connect to. If null, it builds this from host/port with a
* standard configuration. Other JVM's may want to set this value.
*/
public String getUrl() {
if (this.url == null) {
if ((this.host == null) || (this.port == null)) {
return null;
}
return FRONT + this.host + ":" + this.port + BACK;
}
return this.url;
}
@JsonIgnore
public JMXServiceURL getJmxServiceURL() throws IOException {
if(this.pid != null) {
return JMXServiceURLFactory.extractJMXServiceURLFromPid(this.pid);
}
return new JMXServiceURL(getUrl());
}
@JsonIgnore
public boolean isQueriesMultiThreaded() {
return numQueryThreads > 0;
}
public void runOutputWriters(Query query, Iterable<Result> results) throws Exception {
for (OutputWriter writer : outputWriters) {
writer.doWrite(this, query, results);
}
logger.debug("Finished running outputWriters for query: {}", query);
}
/**
* Factory to create a JMXServiceURL from a pid. Inner class to prevent class
* loader issues when tools.jar isn't present.
*/
private static class JMXServiceURLFactory {
private JMXServiceURLFactory() {}
public static JMXServiceURL extractJMXServiceURLFromPid(String pid) throws IOException {
try {
VirtualMachine vm = VirtualMachine.attach(pid);
try {
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (connectorAddress == null) {
String agent = vm.getSystemProperties().getProperty("java.home") +
File.separator + "lib" + File.separator + "management-agent.jar";
vm.loadAgent(agent);
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
}
return new JMXServiceURL(connectorAddress);
} finally {
vm.detach();
}
}
catch(Exception e) {
throw new IOException(e);
}
}
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(Server server) {
return new Builder(server);
}
@NotThreadSafe
@Accessors(chain = true)
public static final class Builder {
@Setter private String alias;
@Setter private String pid;
@Setter private String host;
@Setter private String port;
@Setter private String username;
@Setter private String password;
@Setter private String protocolProviderPackages;
@Setter private String url;
@Setter private String cronExpression;
@Setter private Integer runPeriodSeconds;
@Setter private Integer numQueryThreads;
@Setter private boolean local;
@Setter private boolean ssl;
private final List<OutputWriterFactory> outputWriterFactories = new ArrayList<>();
private final List<OutputWriter> outputWriters = new ArrayList<>();
private final List<Query> queries = new ArrayList<>();
@Setter private KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool;
private Builder() {}
private Builder(Server server) {
this.alias = server.alias;
this.pid = server.pid;
this.host = server.pid != null ? null : server.host; // let the host be deduced in the constructor
this.port = server.port;
this.username = server.username;
this.password = server.password;
this.protocolProviderPackages = server.protocolProviderPackages;
this.url = server.url;
this.cronExpression = server.cronExpression;
this.runPeriodSeconds = server.runPeriodSeconds;
this.numQueryThreads = server.numQueryThreads;
this.local = server.local;
this.ssl = server.ssl;
this.queries.addAll(server.queries);
this.pool = server.pool;
}
public Builder clearQueries() {
queries.clear();
return this;
}
public Builder addQuery(Query query) {
this.queries.add(query);
return this;
}
public Builder addQueries(Set<Query> queries) {
this.queries.addAll(queries);
return this;
}
public Builder addOutputWriterFactory(OutputWriterFactory outputWriterFactory) {
this.outputWriterFactories.add(outputWriterFactory);
return this;
}
public Builder addOutputWriters(Collection<OutputWriter> outputWriters) {
this.outputWriters.addAll(outputWriters);
return this;
}
public Server build() {
if (!outputWriterFactories.isEmpty()) {
return new Server(
alias,
pid,
host,
port,
username,
password,
protocolProviderPackages,
url,
cronExpression,
runPeriodSeconds,
numQueryThreads,
local,
ssl,
queries,
outputWriterFactories,
pool);
}
return new Server(
alias,
pid,
host,
port,
username,
password,
protocolProviderPackages,
url,
cronExpression,
runPeriodSeconds,
numQueryThreads,
local,
ssl,
queries,
ImmutableList.copyOf(outputWriters),
pool);
}
}
}
| jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/Server.java | /**
* The MIT License
* Copyright © 2010 JmxTrans team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.jmxtrans.model;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.name.Named;
import com.googlecode.jmxtrans.connections.JMXConnection;
import com.googlecode.jmxtrans.connections.JmxConnectionProvider;
import com.sun.tools.attach.VirtualMachine;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.apache.commons.pool.KeyedObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.NotThreadSafe;
import javax.annotation.concurrent.ThreadSafe;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import static com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion.NON_NULL;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.ImmutableSet.copyOf;
import static javax.management.remote.JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES;
import static javax.naming.Context.SECURITY_CREDENTIALS;
import static javax.naming.Context.SECURITY_PRINCIPAL;
import static javax.management.remote.rmi.RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE;
/**
* Represents a jmx server that we want to connect to. This also stores the
* queries that we want to execute against the server.
*
* @author jon
*/
@JsonSerialize(include = NON_NULL)
@JsonPropertyOrder(value = {
"alias",
"local",
"pid",
"host",
"port",
"username",
"password",
"cronExpression",
"numQueryThreads",
"protocolProviderPackages"
})
@Immutable
@ThreadSafe
@EqualsAndHashCode(exclude = {"queries", "pool", "outputWriters", "outputWriterFactories"})
@ToString(of = {"pid", "host", "port", "url", "cronExpression", "numQueryThreads"})
public class Server implements JmxConnectionProvider {
private static final String CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
private static final String FRONT = "service:jmx:rmi:///jndi/rmi://";
private static final String BACK = "/jmxrmi";
private static final int DEFAULT_SOCKET_SO_TIMEOUT_MILLIS = 10000;
private static final Logger logger = LoggerFactory.getLogger(Server.class);
/** Returns id for internal logic */
@Getter private final String id;
/**
* Some writers (GraphiteWriter) use the alias in generation of the unique
* key which references this server.
*/
@Getter private final String alias;
/** Returns the pid of the local process jmxtrans will attach to. */
@Getter private final String pid;
private final String host;
private final String port;
@Getter private final String username;
@Getter private final String password;
/**
* This is some obtuse shit for enabling weblogic support.
* <p/>
* http://download.oracle.com/docs/cd/E13222_01/wls/docs90/jmx/accessWLS.
* html
* <p/>
* You'd set this to: weblogic.management.remote
*/
@Getter private final String protocolProviderPackages;
private final String url;
/**
* Each server can set a cronExpression for the scheduler. If the
* cronExpression is null, then the job is run immediately and once.
* Otherwise, it is added to the scheduler for immediate execution and run
* according to the cronExpression.
*
* @deprecated use runPeriodSeconds instead
*/
@Deprecated
@Getter @Nullable private final String cronExpression;
@Getter @Nullable private final Integer runPeriodSeconds;
/** The number of query threads for this server. */
@Getter private final int numQueryThreads;
/**
* Whether the current local Java process should be used or not (useful for
* polling the embedded JVM when using JmxTrans inside a JVM to poll JMX
* stats and push them remotely)
*/
@Getter private final boolean local;
/**
* Whether the remote JMX server should be requested through SSL connection
*/
@Getter private final boolean ssl;
@Getter private final ImmutableSet<Query> queries;
@Nonnull @Getter private final Iterable<OutputWriter> outputWriters;
@Nonnull private final KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool;
@Nonnull @Getter private final ImmutableList<OutputWriterFactory> outputWriterFactories;
@JsonCreator
public Server(
@JsonProperty("alias") String alias,
@JsonProperty("pid") String pid,
@JsonProperty("host") String host,
@JsonProperty("port") String port,
@JsonProperty("username") String username,
@JsonProperty("password") String password,
@JsonProperty("protocolProviderPackages") String protocolProviderPackages,
@JsonProperty("url") String url,
@JsonProperty("cronExpression") String cronExpression,
@JsonProperty("runPeriodSeconds") Integer runPeriodSeconds,
@JsonProperty("numQueryThreads") Integer numQueryThreads,
@JsonProperty("local") boolean local,
@JsonProperty("ssl") boolean ssl,
@JsonProperty("queries") List<Query> queries,
@JsonProperty("outputWriters") List<OutputWriterFactory> outputWriters,
@JacksonInject @Named("mbeanPool") KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool) {
this(alias, pid, host, port, username, password, protocolProviderPackages, url, cronExpression,
runPeriodSeconds, numQueryThreads, local, ssl, queries, outputWriters, ImmutableList.<OutputWriter>of(),
pool);
}
public Server(
String alias,
String pid,
String host,
String port,
String username,
String password,
String protocolProviderPackages,
String url,
String cronExpression,
Integer runPeriodSeconds,
Integer numQueryThreads,
boolean local,
boolean ssl,
List<Query> queries,
ImmutableList<OutputWriter> outputWriters,
KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool) {
this(alias, pid, host, port, username, password, protocolProviderPackages, url, cronExpression,
runPeriodSeconds, numQueryThreads, local, ssl, queries, ImmutableList.<OutputWriterFactory>of(),
outputWriters, pool);
}
private Server(
String alias,
String pid,
String host,
String port,
String username,
String password,
String protocolProviderPackages,
String url,
String cronExpression,
Integer runPeriodSeconds,
Integer numQueryThreads,
boolean local,
boolean ssl,
List<Query> queries,
List<OutputWriterFactory> outputWriterFactories,
List<OutputWriter> outputWriters,
KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool) {
checkArgument(pid != null || url != null || host != null,
"You must provide the pid or the [url|host and port]");
checkArgument(!(pid != null && (url != null || host != null)),
"You must provide the pid OR the url, not both");
this.alias = alias;
this.pid = pid;
this.port = port;
this.username = username;
this.password = password;
this.protocolProviderPackages = protocolProviderPackages;
this.url = url;
this.cronExpression = cronExpression;
if (!isNullOrEmpty(cronExpression)) {
logger.warn("cronExpression is deprecated, please use runPeriodSeconds instead.");
}
this.runPeriodSeconds = runPeriodSeconds;
this.numQueryThreads = firstNonNull(numQueryThreads, 0);
this.local = local;
this.ssl = ssl;
this.queries = copyOf(queries);
// when connecting in local, we cache the host after retrieving it from the network card
if(pid != null) {
try {
this.host = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
// should work, so just throw a runtime if it doesn't
throw new RuntimeException(e);
}
}
else {
this.host = host;
}
this.pool = checkNotNull(pool);
this.outputWriterFactories = ImmutableList.copyOf(firstNonNull(outputWriterFactories, ImmutableList.<OutputWriterFactory>of()));
this.outputWriters = ImmutableList.copyOf(firstNonNull(outputWriters, ImmutableList.<OutputWriter>of()));
this.id = String.format("%s_%s_%s", host, port, pid);
}
public Iterable<Result> execute(Query query) throws Exception {
JMXConnection jmxConnection = null;
try {
jmxConnection = pool.borrowObject(this);
ImmutableList.Builder<Result> results = ImmutableList.builder();
MBeanServerConnection connection = jmxConnection.getMBeanServerConnection();
for (ObjectName queryName : query.queryNames(connection)) {
results.addAll(query.fetchResults(connection, queryName));
}
return results.build();
} catch (Exception e) {
if (jmxConnection != null) {
pool.invalidateObject(this, jmxConnection);
jmxConnection = null;
}
throw e;
}
finally {
if (jmxConnection != null) {
pool.returnObject(this, jmxConnection);
}
}
}
/**
* Generates the proper username/password environment for JMX connections.
*/
@JsonIgnore
public ImmutableMap<String, ?> getEnvironment() {
if (getProtocolProviderPackages() != null && getProtocolProviderPackages().contains("weblogic")) {
ImmutableMap.Builder<String, String> environment = ImmutableMap.builder();
if ((username != null) && (password != null)) {
environment.put(PROTOCOL_PROVIDER_PACKAGES, getProtocolProviderPackages());
environment.put(SECURITY_PRINCIPAL, username);
environment.put(SECURITY_CREDENTIALS, password);
}
return environment.build();
}
ImmutableMap.Builder<String, Object> environment = ImmutableMap.builder();
if ((username != null) && (password != null)) {
String[] credentials = new String[] {
username,
password
};
environment.put(JMXConnector.CREDENTIALS, credentials);
}
JmxTransRMIClientSocketFactory rmiClientSocketFactory = new JmxTransRMIClientSocketFactory(DEFAULT_SOCKET_SO_TIMEOUT_MILLIS, ssl);
// The following is required when JMX is secured with SSL
// with com.sun.management.jmxremote.ssl=true
// as shown in http://docs.oracle.com/javase/8/docs/technotes/guides/management/agent.html#gdfvq
environment.put(RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, rmiClientSocketFactory);
// The following is required when JNDI Registry is secured with SSL
// with com.sun.management.jmxremote.registry.ssl=true
// This property is defined in com.sun.jndi.rmi.registry.RegistryContext.SOCKET_FACTORY
environment.put("com.sun.jndi.rmi.factory.socket", rmiClientSocketFactory);
return environment.build();
}
/**
* Helper method for connecting to a Server. You need to close the resulting
* connection.
*/
@Override
@JsonIgnore
public JMXConnector getServerConnection() throws IOException {
JMXServiceURL url = getJmxServiceURL();
return JMXConnectorFactory.connect(url, this.getEnvironment());
}
@Override
@JsonIgnore
public MBeanServer getLocalMBeanServer() {
// Getting the platform MBean server is cheap (expect for th first call) no need to cache it.
return ManagementFactory.getPlatformMBeanServer();
}
@JsonIgnore
public String getLabel() {
return firstNonNull(alias, host);
}
public String getHost() {
if (host == null && url == null) {
return null;
}
if (host != null) {
return host;
}
// removed the caching of the extracted host as it is a very minor
// optimization we should probably pre compute it in the builder and
// throw exception at construction if both url and host are set
// we might also be able to use java.net.URI to parse the URL, but I'm
// not familiar enough with JMX URLs to think of the test cases ...
return url.substring(url.lastIndexOf("//") + 2, url.lastIndexOf(':'));
}
public String getSource() {
if (alias != null) {
return alias;
}
return this.getHost();
}
public String getPort() {
if (port == null && url == null) {
return null;
}
if (this.port != null) {
return port;
}
return extractPortFromUrl(url);
}
private static String extractPortFromUrl(String url) {
String computedPort = url.substring(url.lastIndexOf(':') + 1);
if (computedPort.contains("/")) {
computedPort = computedPort.substring(0, computedPort.indexOf('/'));
}
return computedPort;
}
/**
* The jmx url to connect to. If null, it builds this from host/port with a
* standard configuration. Other JVM's may want to set this value.
*/
public String getUrl() {
if (this.url == null) {
if ((this.host == null) || (this.port == null)) {
return null;
}
return FRONT + this.host + ":" + this.port + BACK;
}
return this.url;
}
@JsonIgnore
public JMXServiceURL getJmxServiceURL() throws IOException {
if(this.pid != null) {
return JMXServiceURLFactory.extractJMXServiceURLFromPid(this.pid);
}
return new JMXServiceURL(getUrl());
}
@JsonIgnore
public boolean isQueriesMultiThreaded() {
return numQueryThreads > 0;
}
public void runOutputWriters(Query query, Iterable<Result> results) throws Exception {
for (OutputWriter writer : outputWriters) {
writer.doWrite(this, query, results);
}
logger.debug("Finished running outputWriters for query: {}", query);
}
/**
* Factory to create a JMXServiceURL from a pid. Inner class to prevent class
* loader issues when tools.jar isn't present.
*/
private static class JMXServiceURLFactory {
private JMXServiceURLFactory() {}
public static JMXServiceURL extractJMXServiceURLFromPid(String pid) throws IOException {
try {
VirtualMachine vm = VirtualMachine.attach(pid);
try {
String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
if (connectorAddress == null) {
String agent = vm.getSystemProperties().getProperty("java.home") +
File.separator + "lib" + File.separator + "management-agent.jar";
vm.loadAgent(agent);
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
}
return new JMXServiceURL(connectorAddress);
} finally {
vm.detach();
}
}
catch(Exception e) {
throw new IOException(e);
}
}
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(Server server) {
return new Builder(server);
}
@NotThreadSafe
@Accessors(chain = true)
public static final class Builder {
@Setter private String alias;
@Setter private String pid;
@Setter private String host;
@Setter private String port;
@Setter private String username;
@Setter private String password;
@Setter private String protocolProviderPackages;
@Setter private String url;
@Setter private String cronExpression;
@Setter private Integer runPeriodSeconds;
@Setter private Integer numQueryThreads;
@Setter private boolean local;
@Setter private boolean ssl;
private final List<OutputWriterFactory> outputWriterFactories = new ArrayList<>();
private final List<OutputWriter> outputWriters = new ArrayList<>();
private final List<Query> queries = new ArrayList<>();
@Setter private KeyedObjectPool<JmxConnectionProvider, JMXConnection> pool;
private Builder() {}
private Builder(Server server) {
this.alias = server.alias;
this.pid = server.pid;
this.host = server.pid != null ? null : server.host; // let the host be deduced in the constructor
this.port = server.port;
this.username = server.username;
this.password = server.password;
this.protocolProviderPackages = server.protocolProviderPackages;
this.url = server.url;
this.cronExpression = server.cronExpression;
this.runPeriodSeconds = server.runPeriodSeconds;
this.numQueryThreads = server.numQueryThreads;
this.local = server.local;
this.ssl = server.ssl;
this.queries.addAll(server.queries);
this.pool = server.pool;
}
public Builder clearQueries() {
queries.clear();
return this;
}
public Builder addQuery(Query query) {
this.queries.add(query);
return this;
}
public Builder addQueries(Set<Query> queries) {
this.queries.addAll(queries);
return this;
}
public Builder addOutputWriterFactory(OutputWriterFactory outputWriterFactory) {
this.outputWriterFactories.add(outputWriterFactory);
return this;
}
public Builder addOutputWriters(Collection<OutputWriter> outputWriters) {
this.outputWriters.addAll(outputWriters);
return this;
}
public Server build() {
if (!outputWriterFactories.isEmpty()) {
return new Server(
alias,
pid,
host,
port,
username,
password,
protocolProviderPackages,
url,
cronExpression,
runPeriodSeconds,
numQueryThreads,
local,
ssl,
queries,
outputWriterFactories,
pool);
}
return new Server(
alias,
pid,
host,
port,
username,
password,
protocolProviderPackages,
url,
cronExpression,
runPeriodSeconds,
numQueryThreads,
local,
ssl,
queries,
ImmutableList.copyOf(outputWriters),
pool);
}
}
}
| added GetAlias type definition
| jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/Server.java | added GetAlias type definition |
|
Java | mit | ace584d29421515920715977d88006f69172374d | 0 | JetBrains/ideavim,JetBrains/ideavim | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2020 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.group;
import com.google.common.collect.Lists;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.RoamingType;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.markup.*;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.Ref;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.CommandFlags;
import com.maddyhome.idea.vim.common.CharacterPosition;
import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.ex.ranges.LineRange;
import com.maddyhome.idea.vim.helper.*;
import com.maddyhome.idea.vim.option.ListOption;
import com.maddyhome.idea.vim.option.OptionChangeListener;
import com.maddyhome.idea.vim.option.OptionsManager;
import com.maddyhome.idea.vim.regexp.CharPointer;
import com.maddyhome.idea.vim.regexp.CharacterClasses;
import com.maddyhome.idea.vim.regexp.RegExp;
import com.maddyhome.idea.vim.ui.ModalEntry;
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel;
import kotlin.jvm.functions.Function1;
import org.jdom.Element;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import static com.maddyhome.idea.vim.helper.SearchHelperKtKt.shouldIgnoreCase;
@State(name = "VimSearchSettings", storages = {
@Storage(value = "$APP_CONFIG$/vim_settings_local.xml", roamingType = RoamingType.DISABLED)
})
public class SearchGroup implements PersistentStateComponent<Element> {
public SearchGroup() {
final OptionsManager options = OptionsManager.INSTANCE;
options.getHlsearch().addOptionChangeListener((oldValue, newValue) -> {
resetShowSearchHighlight();
forceUpdateSearchHighlights();
});
final OptionChangeListener<Boolean> updateHighlightsIfVisible = (oldValue, newValue) -> {
if (showSearchHighlight) {
forceUpdateSearchHighlights();
}
};
options.getIgnorecase().addOptionChangeListener(updateHighlightsIfVisible);
options.getSmartcase().addOptionChangeListener(updateHighlightsIfVisible);
}
public void turnOn() {
updateSearchHighlights();
}
public void turnOff() {
final boolean show = showSearchHighlight;
clearSearchHighlight();
showSearchHighlight = show;
}
public @Nullable String getLastSearch() {
return lastSearch;
}
// This method is used in AceJump integration plugin
@SuppressWarnings("unused")
public int getLastDir() {
return lastDir.toInt();
}
public @Nullable String getLastPattern() {
return lastPattern;
}
public void resetState() {
lastSearch = lastPattern = lastSubstitute = lastReplace = lastOffset = null;
lastIgnoreSmartCase = false;
lastDir = Direction.UNSET;
resetShowSearchHighlight();
}
private void setLastPattern(@NotNull String lastPattern) {
this.lastPattern = lastPattern;
VimPlugin.getRegister().storeTextSpecial(RegisterGroup.LAST_SEARCH_REGISTER, lastPattern);
VimPlugin.getHistory().addEntry(HistoryGroup.SEARCH, lastPattern);
}
// This method should not be private because it's used in external plugins
@SuppressWarnings("WeakerAccess")
public static @NotNull List<TextRange> findAll(@NotNull Editor editor,
@NotNull String pattern,
int startLine,
int endLine,
boolean ignoreCase) {
final List<TextRange> results = Lists.newArrayList();
final int lineCount = EditorHelper.getLineCount(editor);
final int actualEndLine = endLine == -1 ? lineCount : endLine;
final RegExp.regmmatch_T regMatch = new RegExp.regmmatch_T();
final RegExp regExp = new RegExp();
regMatch.regprog = regExp.vim_regcomp(pattern, 1);
if (regMatch.regprog == null) {
return results;
}
regMatch.rmm_ic = ignoreCase;
int col = 0;
for (int line = startLine; line <= actualEndLine; ) {
int matchedLines = regExp.vim_regexec_multi(regMatch, editor, lineCount, line, col);
if (matchedLines > 0) {
final CharacterPosition startPos = new CharacterPosition(line + regMatch.startpos[0].lnum,
regMatch.startpos[0].col);
final CharacterPosition endPos = new CharacterPosition(line + regMatch.endpos[0].lnum,
regMatch.endpos[0].col);
int start = startPos.toOffset(editor);
int end = endPos.toOffset(editor);
results.add(new TextRange(start, end));
if (start != end) {
line += matchedLines - 1;
col = endPos.column;
}
else {
line += matchedLines;
col = 0;
}
}
else {
line++;
col = 0;
}
}
return results;
}
private static @NotNull ReplaceConfirmationChoice confirmChoice(@NotNull Editor editor, @NotNull String match, @NotNull Caret caret, int startoff) {
final Ref<ReplaceConfirmationChoice> result = Ref.create(ReplaceConfirmationChoice.QUIT);
final Function1<KeyStroke, Boolean> keyStrokeProcessor = key -> {
final ReplaceConfirmationChoice choice;
final char c = key.getKeyChar();
if (StringHelper.isCloseKeyStroke(key) || c == 'q') {
choice = ReplaceConfirmationChoice.QUIT;
} else if (c == 'y') {
choice = ReplaceConfirmationChoice.SUBSTITUTE_THIS;
} else if (c == 'l') {
choice = ReplaceConfirmationChoice.SUBSTITUTE_LAST;
} else if (c == 'n') {
choice = ReplaceConfirmationChoice.SKIP;
} else if (c == 'a') {
choice = ReplaceConfirmationChoice.SUBSTITUTE_ALL;
} else {
return true;
}
result.set(choice);
return false;
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
MotionGroup.moveCaret(editor, caret, startoff);
final TestInputModel inputModel = TestInputModel.getInstance(editor);
for (KeyStroke key = inputModel.nextKeyStroke(); key != null; key = inputModel.nextKeyStroke()) {
if (!keyStrokeProcessor.invoke(key)) {
break;
}
}
}
else {
// XXX: The Ex entry panel is used only for UI here, its logic might be inappropriate for this method
final ExEntryPanel exEntryPanel = ExEntryPanel.getInstanceWithoutShortcuts();
exEntryPanel.activate(editor, new EditorDataContext(editor, null), MessageHelper.message("replace.with.0", match), "", 1);
MotionGroup.moveCaret(editor, caret, startoff);
ModalEntry.INSTANCE.activate(keyStrokeProcessor);
exEntryPanel.deactivate(true, false);
}
return result.get();
}
public int search(@NotNull Editor editor, @NotNull String command, int count, EnumSet<CommandFlags> flags, boolean moveCursor) {
return search(editor, editor.getCaretModel().getPrimaryCaret(), command, count, flags, moveCursor);
}
public int search(@NotNull Editor editor, @NotNull Caret caret, @NotNull String command, int count, EnumSet<CommandFlags> flags,
boolean moveCursor) {
final int res = search(editor, command, caret.getOffset(), count, flags);
if (res != -1 && moveCursor) {
VimPlugin.getMark().saveJumpLocation(editor);
MotionGroup.moveCaret(editor, caret, res);
}
return res;
}
public int search(@NotNull Editor editor, @NotNull String command, int startOffset, int count, @NotNull EnumSet<CommandFlags> flags) {
Direction dir = Direction.FORWARDS;
char type = '/';
String pattern = lastSearch;
String offset = lastOffset;
if (flags.contains(CommandFlags.FLAG_SEARCH_REV)) {
dir = Direction.BACKWARDS;
type = '?';
}
if (command.length() > 0) {
if (command.charAt(0) != type) {
CharPointer p = new CharPointer(command);
CharPointer end = RegExp.skip_regexp(p.ref(0), type, true);
pattern = p.substring(end.pointer() - p.pointer());
if (logger.isDebugEnabled()) logger.debug("pattern=" + pattern);
if (p.charAt() != type) {
if (end.charAt() == type) {
end.inc();
offset = end.toString();
} else {
logger.debug("no offset");
offset = "";
}
}
else {
p.inc();
offset = p.toString();
if (logger.isDebugEnabled()) logger.debug("offset=" + offset);
}
}
else if (command.length() == 1) {
offset = "";
}
else {
offset = command.substring(1);
if (logger.isDebugEnabled()) logger.debug("offset=" + offset);
}
}
lastSearch = pattern;
lastIgnoreSmartCase = false;
if (pattern != null) {
setLastPattern(pattern);
}
lastOffset = offset;
lastDir = dir;
if (logger.isDebugEnabled()) {
logger.debug("lastSearch=" + lastSearch);
logger.debug("lastOffset=" + lastOffset);
logger.debug("lastDir=" + lastDir);
}
resetShowSearchHighlight();
forceUpdateSearchHighlights();
return findItOffset(editor, startOffset, count, lastDir);
}
public int searchWord(@NotNull Editor editor, @NotNull Caret caret, int count, boolean whole, Direction dir) {
TextRange range = SearchHelper.findWordUnderCursor(editor, caret);
if (range == null) {
logger.warn("No range was found");
return -1;
}
StringBuilder pattern = new StringBuilder();
if (whole) {
pattern.append("\\<");
}
pattern.append(EditorHelper.getText(editor, range.getStartOffset(), range.getEndOffset()));
if (whole) {
pattern.append("\\>");
}
MotionGroup.moveCaret(editor, caret, range.getStartOffset());
lastSearch = pattern.toString();
lastIgnoreSmartCase = true;
setLastPattern(lastSearch);
lastOffset = "";
lastDir = dir;
resetShowSearchHighlight();
forceUpdateSearchHighlights();
return findItOffset(editor, caret.getOffset(), count, lastDir);
}
public int searchNext(@NotNull Editor editor, @NotNull Caret caret, int count) {
return searchNextWithDirection(editor, caret, count, lastDir);
}
public int searchPrevious(@NotNull Editor editor, @NotNull Caret caret, int count) {
return searchNextWithDirection(editor, caret, count, lastDir.reverse());
}
public int searchNextFromOffset(@NotNull Editor editor, int offset, int count) {
resetShowSearchHighlight();
updateSearchHighlights();
return findItOffset(editor, offset, count, Direction.FORWARDS);
}
private int searchNextWithDirection(@NotNull Editor editor, @NotNull Caret caret, int count, Direction dir) {
resetShowSearchHighlight();
updateSearchHighlights();
final int startOffset = caret.getOffset();
int offset = findItOffset(editor, startOffset, count, dir);
if (offset == startOffset) {
/* Avoid getting stuck on the current cursor position, which can
* happen when an offset is given and the cursor is on the last char
* in the buffer: Repeat with count + 1. */
offset = findItOffset(editor, startOffset, count + 1, dir);
}
return offset;
}
private void resetShowSearchHighlight() {
showSearchHighlight = OptionsManager.INSTANCE.getHlsearch().isSet();
}
public void clearSearchHighlight() {
showSearchHighlight = false;
updateSearchHighlights();
}
private void forceUpdateSearchHighlights() {
SearchHighlightsHelper.updateSearchHighlights(lastSearch, lastIgnoreSmartCase, showSearchHighlight, true);
}
private void updateSearchHighlights() {
SearchHighlightsHelper.updateSearchHighlights(lastSearch, lastIgnoreSmartCase, showSearchHighlight, false);
}
public void resetIncsearchHighlights() {
SearchHighlightsHelper.updateSearchHighlights(lastSearch, lastIgnoreSmartCase, showSearchHighlight, true);
}
private void highlightSearchLines(@NotNull Editor editor, int startLine, int endLine) {
if (lastSearch != null) {
final List<TextRange> results = findAll(editor, lastSearch, startLine, endLine,
shouldIgnoreCase(lastSearch, lastIgnoreSmartCase));
SearchHighlightsHelper.highlightSearchResults(editor, lastSearch, results, -1);
}
}
public @Nullable TextRange getNextSearchRange(@NotNull Editor editor, int count, boolean forwards) {
editor.getCaretModel().removeSecondaryCarets();
TextRange current = findUnderCaret(editor);
if (current == null || CommandStateHelper.inVisualMode(editor) && atEdgeOfGnRange(current, editor, forwards)) {
current = findNextSearchForGn(editor, count, forwards);
}
else if (count > 1) {
current = findNextSearchForGn(editor, count - 1, forwards);
}
return current;
}
private boolean atEdgeOfGnRange(@NotNull TextRange nextRange, @NotNull Editor editor, boolean forwards) {
int currentPosition = editor.getCaretModel().getOffset();
if (forwards) {
return nextRange.getEndOffset() - VimPlugin.getVisualMotion().getSelectionAdj() == currentPosition;
}
else {
return nextRange.getStartOffset() == currentPosition;
}
}
private @Nullable TextRange findNextSearchForGn(@NotNull Editor editor, int count, boolean forwards) {
if (forwards) {
final EnumSet<SearchOptions> searchOptions = EnumSet.of(SearchOptions.WRAP, SearchOptions.WHOLE_FILE);
return findIt(editor, lastSearch, editor.getCaretModel().getOffset(), count, searchOptions);
} else {
return searchBackward(editor, editor.getCaretModel().getOffset(), count);
}
}
private @Nullable TextRange findUnderCaret(@NotNull Editor editor) {
final TextRange backSearch = searchBackward(editor, editor.getCaretModel().getOffset() + 1, 1);
if (backSearch == null) return null;
return backSearch.contains(editor.getCaretModel().getOffset()) ? backSearch : null;
}
private @Nullable TextRange searchBackward(@NotNull Editor editor, int offset, int count) {
// Backward search returns wrongs end offset for some cases. That's why we should perform additional forward search
final EnumSet<SearchOptions> searchOptions = EnumSet.of(SearchOptions.WRAP, SearchOptions.WHOLE_FILE, SearchOptions.BACKWARDS);
final TextRange foundBackward = findIt(editor, lastSearch, offset, count, searchOptions);
if (foundBackward == null) return null;
int startOffset = foundBackward.getStartOffset() - 1;
if (startOffset < 0) startOffset = EditorHelperRt.getFileSize(editor);
searchOptions.remove(SearchOptions.BACKWARDS);
return findIt(editor, lastSearch, startOffset, 1, searchOptions);
}
public static TextRange findIt(@NotNull Editor editor, @Nullable String pattern, int startOffset, int count, EnumSet<SearchOptions> searchOptions) {
if (pattern == null || pattern.length() == 0) {
logger.warn("Pattern is null or empty. Cannot perform search");
return null;
}
Direction dir = searchOptions.contains(SearchOptions.BACKWARDS) ? Direction.BACKWARDS : Direction.FORWARDS;
//RE sp;
RegExp sp;
RegExp.regmmatch_T regmatch = new RegExp.regmmatch_T();
regmatch.rmm_ic = shouldIgnoreCase(pattern, searchOptions.contains(SearchOptions.IGNORE_SMARTCASE));
sp = new RegExp();
regmatch.regprog = sp.vim_regcomp(pattern, 1);
if (regmatch.regprog == null) {
if (logger.isDebugEnabled()) logger.debug("bad pattern: " + pattern);
return null;
}
/*
int extra_col = 1;
int startcol = -1;
boolean found = false;
boolean match_ok = true;
LogicalPosition pos = editor.offsetToLogicalPosition(startOffset);
LogicalPosition endpos = null;
//REMatch match = null;
*/
CharacterPosition lpos = CharacterPosition.Companion.fromOffset(editor, startOffset);
RegExp.lpos_T pos = new RegExp.lpos_T();
pos.lnum = lpos.line;
pos.col = lpos.column;
int found;
int lnum; /* no init to shut up Apollo cc */
//RegExp.regmmatch_T regmatch;
CharPointer ptr;
int matchcol;
RegExp.lpos_T matchpos;
RegExp.lpos_T endpos = new RegExp.lpos_T();
int loop;
RegExp.lpos_T start_pos;
boolean at_first_line;
int extra_col = dir == Direction.FORWARDS ? 1 : 0;
boolean match_ok;
long nmatched;
//int submatch = 0;
boolean first_match = true;
int lineCount = EditorHelper.getLineCount(editor);
int startLine = 0;
int endLine = lineCount;
do /* loop for count */ {
start_pos = new RegExp.lpos_T(pos); /* remember start pos for detecting no match */
found = 0; /* default: not found */
at_first_line = true; /* default: start in first line */
if (pos.lnum == -1) /* correct lnum for when starting in line 0 */ {
pos.lnum = 0;
pos.col = 0;
at_first_line = false; /* not in first line now */
}
/*
* Start searching in current line, unless searching backwards and
* we're in column 0.
*/
if (dir == Direction.BACKWARDS && start_pos.col == 0) {
lnum = pos.lnum - 1;
at_first_line = false;
}
else {
lnum = pos.lnum;
}
int lcount = EditorHelper.getLineCount(editor);
for (loop = 0; loop <= 1; ++loop) /* loop twice if 'wrapscan' set */ {
if (!searchOptions.contains(SearchOptions.WHOLE_FILE)) {
startLine = lnum;
endLine = lnum + 1;
}
for (; lnum >= startLine && lnum < endLine; lnum += dir.toInt(), at_first_line = false) {
/*
* Look for a match somewhere in the line.
*/
nmatched = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, 0);
if (nmatched > 0) {
/* match may actually be in another line when using \zs */
matchpos = new RegExp.lpos_T(regmatch.startpos[0]);
endpos = new RegExp.lpos_T(regmatch.endpos[0]);
ptr = new CharPointer(EditorHelper.getLineBuffer(editor, lnum + matchpos.lnum));
/*
* Forward search in the first line: match should be after
* the start position. If not, continue at the end of the
* match (this is vi compatible) or on the next char.
*/
if (dir == Direction.FORWARDS && at_first_line) {
match_ok = true;
/*
* When match lands on a NUL the cursor will be put
* one back afterwards, compare with that position,
* otherwise "/$" will get stuck on end of line.
*/
while (matchpos.lnum == 0
&& (searchOptions.contains(SearchOptions.WANT_ENDPOS) && first_match
? (nmatched == 1 && endpos.col - 1 < start_pos.col + extra_col)
: (matchpos.col - (ptr.charAt(matchpos.col) == '\u0000' ? 1 : 0) < start_pos.col + extra_col))) {
if (nmatched > 1) {
/* end is in next line, thus no match in
* this line */
match_ok = false;
break;
}
matchcol = endpos.col;
/* for empty match: advance one char */
if (matchcol == matchpos.col && ptr.charAt(matchcol) != '\u0000') {
++matchcol;
}
if (ptr.charAt(matchcol) == '\u0000' ||
(nmatched = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, matchcol)) == 0) {
match_ok = false;
break;
}
matchpos = new RegExp.lpos_T(regmatch.startpos[0]);
endpos = new RegExp.lpos_T(regmatch.endpos[0]);
/* Need to get the line pointer again, a
* multi-line search may have made it invalid. */
ptr = new CharPointer(EditorHelper.getLineBuffer(editor, lnum));
}
if (!match_ok) {
continue;
}
}
if (dir == Direction.BACKWARDS) {
/*
* Now, if there are multiple matches on this line,
* we have to get the last one. Or the last one before
* the cursor, if we're on that line.
* When putting the new cursor at the end, compare
* relative to the end of the match.
*/
match_ok = false;
for (;;) {
if (loop != 0 ||
(searchOptions.contains(SearchOptions.WANT_ENDPOS)
? (lnum + regmatch.endpos[0].lnum < start_pos.lnum || (lnum + regmatch.endpos[0].lnum == start_pos.lnum && regmatch.endpos[0].col - 1 < start_pos.col + extra_col))
: (lnum + regmatch.startpos[0].lnum < start_pos.lnum || (lnum + regmatch.startpos[0].lnum == start_pos.lnum && regmatch.startpos[0].col < start_pos.col + extra_col)))) {
/* Remember this position, we use it if it's
* the last match in the line. */
match_ok = true;
matchpos = new RegExp.lpos_T(regmatch.startpos[0]);
endpos = new RegExp.lpos_T(regmatch.endpos[0]);
}
else {
break;
}
/*
* We found a valid match, now check if there is
* another one after it.
* If vi-compatible searching, continue at the end
* of the match, otherwise continue one position
* forward.
*/
if (nmatched > 1) {
break;
}
matchcol = endpos.col;
/* for empty match: advance one char */
if (matchcol == matchpos.col && ptr.charAt(matchcol) != '\u0000') {
++matchcol;
}
if (ptr.charAt(matchcol) == '\u0000' ||
(nmatched = sp.vim_regexec_multi(regmatch, editor, lcount, lnum + matchpos.lnum, matchcol)) == 0) {
break;
}
/* Need to get the line pointer again, a
* multi-line search may have made it invalid. */
ptr = new CharPointer(EditorHelper.getLineBuffer(editor, lnum + matchpos.lnum));
}
/*
* If there is only a match after the cursor, skip
* this match.
*/
if (!match_ok) {
continue;
}
}
pos.lnum = lnum + matchpos.lnum;
pos.col = matchpos.col;
endpos.lnum = lnum + endpos.lnum;
found = 1;
first_match = false;
/* Set variables used for 'incsearch' highlighting. */
//search_match_lines = endpos.lnum - (lnum - first_lnum);
//search_match_endcol = endpos.col;
break;
}
//line_breakcheck(); /* stop if ctrl-C typed */
//if (got_int)
// break;
if (loop != 0 && lnum == start_pos.lnum) {
break; /* if second loop, stop where started */
}
}
at_first_line = false;
/*
* stop the search if wrapscan isn't set, after an interrupt and
* after a match
*/
if (!searchOptions.contains(SearchOptions.WRAP) || found != 0) {
break;
}
/*
* If 'wrapscan' is set we continue at the other end of the file.
* If 'shortmess' does not contain 's', we give a message.
* This message is also remembered in keep_msg for when the screen
* is redrawn. The keep_msg is cleared whenever another message is
* written.
*/
if (dir == Direction.BACKWARDS) /* start second loop at the other end */ {
lnum = lineCount - 1;
//if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG))
// give_warning((char_u *)_(top_bot_msg), TRUE);
}
else {
lnum = 0;
//if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG))
// give_warning((char_u *)_(bot_top_msg), TRUE);
}
}
//if (got_int || called_emsg || break_loop)
// break;
}
while (--count > 0 && found != 0); /* stop after count matches or no match */
if (found == 0) /* did not find it */ {
//if ((options & SEARCH_MSG) == SEARCH_MSG)
if (searchOptions.contains(SearchOptions.SHOW_MESSAGES)) {
if (searchOptions.contains(SearchOptions.WRAP)) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern));
}
else if (lnum <= 0) {
VimPlugin.showMessage(MessageHelper.message(Msg.E384, pattern));
}
else {
VimPlugin.showMessage(MessageHelper.message(Msg.E385, pattern));
}
}
return null;
}
//return new TextRange(editor.logicalPositionToOffset(new LogicalPosition(pos.lnum, pos.col)),
// editor.logicalPositionToOffset(new LogicalPosition(endpos.lnum, endpos.col)));
//return new TextRange(editor.logicalPositionToOffset(new LogicalPosition(pos.lnum, 0)) + pos.col,
// editor.logicalPositionToOffset(new LogicalPosition(endpos.lnum, 0)) + endpos.col);
return new TextRange(new CharacterPosition(pos.lnum, pos.col).toOffset(editor),
new CharacterPosition(endpos.lnum, endpos.col).toOffset(editor));
}
private int findItOffset(@NotNull Editor editor, int startOffset, int count, Direction dir) {
boolean wrap = OptionsManager.INSTANCE.getWrapscan().isSet();
logger.debug("Perform search. Direction: " + dir + " wrap: " + wrap);
int offset = 0;
boolean offsetIsLineOffset = false;
boolean hasEndOffset = false;
ParsePosition pp = new ParsePosition(0);
if (lastOffset == null) {
logger.warn("Last offset is null. Cannot perform search");
return -1;
}
if (lastOffset.length() > 0) {
if (Character.isDigit(lastOffset.charAt(0)) || lastOffset.charAt(0) == '+' || lastOffset.charAt(0) == '-') {
offsetIsLineOffset = true;
if (lastOffset.equals("+")) {
offset = 1;
} else if (lastOffset.equals("-")) {
offset = -1;
} else {
if (lastOffset.charAt(0) == '+') {
lastOffset = lastOffset.substring(1);
}
NumberFormat nf = NumberFormat.getIntegerInstance();
pp = new ParsePosition(0);
Number num = nf.parse(lastOffset, pp);
if (num != null) {
offset = num.intValue();
}
}
} else if ("ebs".indexOf(lastOffset.charAt(0)) != -1) {
if (lastOffset.length() >= 2) {
if ("+-".indexOf(lastOffset.charAt(1)) != -1) {
offset = 1;
}
NumberFormat nf = NumberFormat.getIntegerInstance();
pp = new ParsePosition(lastOffset.charAt(1) == '+' ? 2 : 1);
Number num = nf.parse(lastOffset, pp);
if (num != null) {
offset = num.intValue();
}
}
hasEndOffset = lastOffset.charAt(0) == 'e';
}
}
/*
* If there is a character offset, subtract it from the current
* position, so we don't get stuck at "?pat?e+2" or "/pat/s-2".
* Skip this if pos.col is near MAXCOL (closed fold).
* This is not done for a line offset, because then we would not be vi
* compatible.
*/
if (!offsetIsLineOffset && offset != 0) {
startOffset = Math.max(0, Math.min(startOffset - offset, EditorHelperRt.getFileSize(editor) - 1));
}
EnumSet<SearchOptions> searchOptions = EnumSet.of(SearchOptions.SHOW_MESSAGES, SearchOptions.WHOLE_FILE);
if (dir == Direction.BACKWARDS) searchOptions.add(SearchOptions.BACKWARDS);
if (lastIgnoreSmartCase) searchOptions.add(SearchOptions.IGNORE_SMARTCASE);
if (wrap) searchOptions.add(SearchOptions.WRAP);
if (hasEndOffset) searchOptions.add(SearchOptions.WANT_ENDPOS);
TextRange range = findIt(editor, lastSearch, startOffset, count, searchOptions);
if (range == null) {
logger.warn("No range is found");
return -1;
}
int res = range.getStartOffset();
if (offsetIsLineOffset) {
int line = editor.offsetToLogicalPosition(range.getStartOffset()).line;
int newLine = EditorHelper.normalizeLine(editor, line + offset);
res = VimPlugin.getMotion().moveCaretToLineStart(editor, newLine);
}
else if (hasEndOffset || offset != 0) {
int base = hasEndOffset ? range.getEndOffset() - 1 : range.getStartOffset();
res = Math.max(0, Math.min(base + offset, EditorHelperRt.getFileSize(editor) - 1));
}
int ppos = pp.getIndex();
if (ppos < lastOffset.length() - 1 && lastOffset.charAt(ppos) == ';') {
EnumSet<CommandFlags> flags = EnumSet.noneOf(CommandFlags.class);
if (lastOffset.charAt(ppos + 1) == '/') {
flags.add(CommandFlags.FLAG_SEARCH_FWD);
}
else if (lastOffset.charAt(ppos + 1) == '?') {
flags.add(CommandFlags.FLAG_SEARCH_REV);
}
else {
return res;
}
if (lastOffset.length() - ppos > 2) {
ppos++;
}
res = search(editor, lastOffset.substring(ppos + 1), res, 1, flags);
}
return res;
}
@RWLockLabel.SelfSynchronized
public boolean searchAndReplace(@NotNull Editor editor, @NotNull Caret caret, @NotNull LineRange range,
@NotNull @NonNls String excmd, @NonNls String exarg) {
// Explicitly exit visual mode here, so that visual mode marks don't change when we move the cursor to a match.
if (CommandStateHelper.inVisualMode(editor)) {
ModeHelper.exitVisualMode(editor);
}
CharPointer cmd = new CharPointer(new StringBuffer(exarg));
int which_pat;
if ("~".equals(excmd)) {
which_pat = RE_LAST; /* use last used regexp */
}
else {
which_pat = RE_SUBST; /* use last substitute regexp */
}
CharPointer pat;
CharPointer sub;
char delimiter;
/* new pattern and substitution */
if (excmd.charAt(0) == 's' && !cmd.isNul() && !Character.isWhitespace(
cmd.charAt()) && "0123456789cegriIp|\"".indexOf(cmd.charAt()) == -1) {
/* don't accept alphanumeric for separator */
if (CharacterClasses.isAlpha(cmd.charAt())) {
VimPlugin.showMessage(MessageHelper.message(Msg.E146));
return false;
}
/*
* undocumented vi feature:
* "\/sub/" and "\?sub?" use last used search pattern (almost like
* //sub/r). "\&sub&" use last substitute pattern (like //sub/).
*/
if (cmd.charAt() == '\\') {
cmd.inc();
if ("/?&".indexOf(cmd.charAt()) == -1) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_backslash));
return false;
}
if (cmd.charAt() != '&') {
which_pat = RE_SEARCH; /* use last '/' pattern */
}
pat = new CharPointer(""); /* empty search pattern */
delimiter = cmd.charAt(); /* remember delimiter character */
cmd.inc();
}
else {
/* find the end of the regexp */
which_pat = RE_LAST; /* use last used regexp */
delimiter = cmd.charAt(); /* remember delimiter character */
cmd.inc();
pat = cmd.ref(0); /* remember start of search pat */
cmd = RegExp.skip_regexp(cmd, delimiter, true);
if (cmd.charAt() == delimiter) /* end delimiter found */ {
cmd.set('\u0000').inc(); /* replace it with a NUL */
}
}
/*
* Small incompatibility: vi sees '\n' as end of the command, but in
* Vim we want to use '\n' to find/substitute a NUL.
*/
sub = cmd.ref(0); /* remember the start of the substitution */
while (!cmd.isNul()) {
if (cmd.charAt() == delimiter) /* end delimiter found */ {
cmd.set('\u0000').inc(); /* replace it with a NUL */
break;
}
if (cmd.charAt(0) == '\\' && cmd.charAt(1) != 0) /* skip escaped characters */ {
cmd.inc();
}
cmd.inc();
}
}
else {
/* use previous pattern and substitution */
if (lastReplace == null) {
/* there is no previous command */
VimPlugin.showMessage(MessageHelper.message(Msg.e_nopresub));
return false;
}
pat = null; /* search_regcomp() will use previous pattern */
sub = new CharPointer(lastReplace);
}
/*
* Find trailing options. When '&' is used, keep old options.
*/
if (cmd.charAt() == '&') {
cmd.inc();
}
else {
do_all = OptionsManager.INSTANCE.getGdefault().isSet();
do_ask = false;
do_error = true;
do_ic = 0;
}
while (!cmd.isNul()) {
/*
* Note that 'g' and 'c' are always inverted, also when p_ed is off.
* 'r' is never inverted.
*/
if (cmd.charAt() == 'g') {
do_all = !do_all;
}
else if (cmd.charAt() == 'c') {
do_ask = !do_ask;
}
else if (cmd.charAt() == 'e') {
do_error = !do_error;
}
else if (cmd.charAt() == 'r') {
/* use last used regexp */
which_pat = RE_LAST;
}
else if (cmd.charAt() == 'i') {
/* ignore case */
do_ic = 'i';
}
else if (cmd.charAt() == 'I') {
/* don't ignore case */
do_ic = 'I';
}
else if (cmd.charAt() != 'p') {
break;
}
cmd.inc();
}
int line1 = range.startLine;
int line2 = range.endLine;
if (line1 < 0 || line2 < 0) {
return false;
}
/*
* check for a trailing count
*/
cmd.skipWhitespaces();
if (Character.isDigit(cmd.charAt())) {
int i = cmd.getDigits();
if (i <= 0 && do_error) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_zerocount));
return false;
}
line1 = line2;
line2 = EditorHelper.normalizeLine(editor, line1 + i - 1);
}
/*
* check for trailing command or garbage
*/
cmd.skipWhitespaces();
if (!cmd.isNul() && cmd.charAt() != '"') {
/* if not end-of-line or comment */
VimPlugin.showMessage(MessageHelper.message(Msg.e_trailing));
return false;
}
String pattern = "";
if (pat == null || pat.isNul()) {
switch (which_pat) {
case RE_LAST:
pattern = lastPattern;
break;
case RE_SEARCH:
pattern = lastSearch;
break;
case RE_SUBST:
pattern = lastSubstitute;
break;
}
}
else {
pattern = pat.toString();
}
lastSubstitute = pattern;
lastSearch = pattern;
if (pattern != null) {
setLastPattern(pattern);
}
int start = editor.getDocument().getLineStartOffset(line1);
int end = editor.getDocument().getLineEndOffset(line2);
RegExp sp;
RegExp.regmmatch_T regmatch = new RegExp.regmmatch_T();
sp = new RegExp();
regmatch.regprog = sp.vim_regcomp(pattern, 1);
if (regmatch.regprog == null) {
if (do_error) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_invcmd));
}
return false;
}
/* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
regmatch.rmm_ic = shouldIgnoreCase(pattern != null ? pattern : "", false);
if (do_ic == 'i') {
regmatch.rmm_ic = true;
}
else if (do_ic == 'I') {
regmatch.rmm_ic = false;
}
/*
* ~ in the substitute pattern is replaced with the old pattern.
* We do it here once to avoid it to be replaced over and over again.
* But don't do it when it starts with "\=", then it's an expression.
*/
if (!(sub.charAt(0) == '\\' && sub.charAt(1) == '=') && lastReplace != null) {
StringBuffer tmp = new StringBuffer(sub.toString());
int pos = 0;
while ((pos = tmp.indexOf("~", pos)) != -1) {
if (pos == 0 || tmp.charAt(pos - 1) != '\\') {
tmp.replace(pos, pos + 1, lastReplace);
pos += lastReplace.length();
}
pos++;
}
sub = new CharPointer(tmp);
}
lastReplace = sub.toString();
resetShowSearchHighlight();
forceUpdateSearchHighlights();
if (logger.isDebugEnabled()) {
logger.debug("search range=[" + start + "," + end + "]");
logger.debug("pattern=" + pattern + ", replace=" + sub);
}
int lastMatch = -1;
int lastLine = -1;
int searchcol = 0;
boolean firstMatch = true;
boolean got_quit = false;
int lcount = EditorHelper.getLineCount(editor);
for (int lnum = line1; lnum <= line2 && !got_quit; ) {
CharacterPosition newpos = null;
int nmatch = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, searchcol);
if (nmatch > 0) {
if (firstMatch) {
VimPlugin.getMark().saveJumpLocation(editor);
firstMatch = false;
}
String match = sp.vim_regsub_multi(regmatch, lnum, sub, 1, false);
if (match == null) {
return false;
}
int line = lnum + regmatch.startpos[0].lnum;
CharacterPosition startpos = new CharacterPosition(lnum + regmatch.startpos[0].lnum, regmatch.startpos[0].col);
CharacterPosition endpos = new CharacterPosition(lnum + regmatch.endpos[0].lnum, regmatch.endpos[0].col);
int startoff = startpos.toOffset(editor);
int endoff = endpos.toOffset(editor);
int newend = startoff + match.length();
if (do_all || line != lastLine) {
boolean doReplace = true;
if (do_ask) {
RangeHighlighter hl = SearchHighlightsHelper.addSubstitutionConfirmationHighlight(editor, startoff, endoff);
final ReplaceConfirmationChoice choice = confirmChoice(editor, match, caret, startoff);
editor.getMarkupModel().removeHighlighter(hl);
switch (choice) {
case SUBSTITUTE_THIS:
doReplace = true;
break;
case SKIP:
doReplace = false;
break;
case SUBSTITUTE_ALL:
do_ask = false;
break;
case QUIT:
doReplace = false;
got_quit = true;
break;
case SUBSTITUTE_LAST:
do_all = false;
line2 = lnum;
doReplace = true;
break;
}
}
if (doReplace) {
ApplicationManager.getApplication().runWriteAction(() -> editor.getDocument().replaceString(startoff, endoff, match));
lastMatch = startoff;
newpos = CharacterPosition.Companion.fromOffset(editor, newend);
lnum += newpos.line - endpos.line;
line2 += newpos.line - endpos.line;
}
}
lastLine = line;
lnum += nmatch - 1;
if (do_all && startoff != endoff) {
if (newpos != null) {
lnum = newpos.line;
searchcol = newpos.column;
}
else {
searchcol = endpos.column;
}
}
else {
searchcol = 0;
lnum++;
}
}
else {
lnum++;
searchcol = 0;
}
}
if (lastMatch != -1) {
if (!got_quit) {
MotionGroup.moveCaret(editor, caret,
VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, editor.offsetToLogicalPosition(lastMatch).line));
}
}
else {
VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern));
}
return true;
}
public void saveData(@NotNull Element element) {
logger.debug("saveData");
Element search = new Element("search");
if (lastSearch != null) {
search.addContent(createElementWithText("last-search", lastSearch));
}
if (lastOffset != null) {
search.addContent(createElementWithText("last-offset", lastOffset));
}
if (lastPattern != null) {
search.addContent(createElementWithText("last-pattern", lastPattern));
}
if (lastReplace != null) {
search.addContent(createElementWithText("last-replace", lastReplace));
}
if (lastSubstitute != null) {
search.addContent(createElementWithText("last-substitute", lastSubstitute));
}
Element text = new Element("last-dir");
text.addContent(Integer.toString(lastDir.toInt()));
search.addContent(text);
text = new Element("show-last");
text.addContent(Boolean.toString(showSearchHighlight));
if (logger.isDebugEnabled()) logger.debug("text=" + text);
search.addContent(text);
element.addContent(search);
}
private static @NotNull Element createElementWithText(@NotNull String name, @NotNull String text) {
return StringHelper.setSafeXmlText(new Element(name), text);
}
public void readData(@NotNull Element element) {
logger.debug("readData");
Element search = element.getChild("search");
if (search == null) {
return;
}
lastSearch = getSafeChildText(search, "last-search");
lastOffset = getSafeChildText(search, "last-offset");
lastPattern = getSafeChildText(search, "last-pattern");
lastReplace = getSafeChildText(search, "last-replace");
lastSubstitute = getSafeChildText(search, "last-substitute");
Element dir = search.getChild("last-dir");
lastDir = Direction.Companion.fromInt(Integer.parseInt(dir.getText()));
Element show = search.getChild("show-last");
final ListOption vimInfo = OptionsManager.INSTANCE.getViminfo();
final boolean disableHighlight = vimInfo.contains("h");
showSearchHighlight = !disableHighlight && Boolean.parseBoolean(show.getText());
if (logger.isDebugEnabled()) {
logger.debug("show=" + show + "(" + show.getText() + ")");
logger.debug("showSearchHighlight=" + showSearchHighlight);
}
}
private static @Nullable String getSafeChildText(@NotNull Element element, @NotNull String name) {
final Element child = element.getChild(name);
return child != null ? StringHelper.getSafeXmlText(child) : null;
}
/**
* Updates search highlights when the selected editor changes
*/
@SuppressWarnings("unused")
public static void fileEditorManagerSelectionChangedCallback(@NotNull FileEditorManagerEvent event) {
VimPlugin.getSearch().updateSearchHighlights();
}
@Nullable
@Override
public Element getState() {
Element element = new Element("search");
saveData(element);
return element;
}
@Override
public void loadState(@NotNull Element state) {
readData(state);
}
public static class DocumentSearchListener implements DocumentListener {
public static DocumentSearchListener INSTANCE = new DocumentSearchListener();
@Contract(pure = true)
private DocumentSearchListener () {
}
@Override
public void documentChanged(@NotNull DocumentEvent event) {
for (Project project : ProjectManager.getInstance().getOpenProjects()) {
final Document document = event.getDocument();
for (Editor editor : EditorFactory.getInstance().getEditors(document, project)) {
Collection<RangeHighlighter> hls = UserDataManager.getVimLastHighlighters(editor);
if (hls == null) {
continue;
}
if (logger.isDebugEnabled()) {
logger.debug("hls=" + hls);
logger.debug("event=" + event);
}
// We can only re-highlight whole lines, so clear any highlights in the affected lines
final LogicalPosition startPosition = editor.offsetToLogicalPosition(event.getOffset());
final LogicalPosition endPosition = editor.offsetToLogicalPosition(event.getOffset() + event.getNewLength());
final int startLineOffset = document.getLineStartOffset(startPosition.line);
final int endLineOffset = document.getLineEndOffset(endPosition.line);
final Iterator<RangeHighlighter> iter = hls.iterator();
while (iter.hasNext()) {
final RangeHighlighter highlighter = iter.next();
if (!highlighter.isValid() || (highlighter.getStartOffset() >= startLineOffset && highlighter.getEndOffset() <= endLineOffset)) {
iter.remove();
editor.getMarkupModel().removeHighlighter(highlighter);
}
}
VimPlugin.getSearch().highlightSearchLines(editor, startPosition.line, endPosition.line);
if (logger.isDebugEnabled()) {
hls = UserDataManager.getVimLastHighlighters(editor);
logger.debug("sl=" + startPosition.line + ", el=" + endPosition.line);
logger.debug("hls=" + hls);
}
}
}
}
}
private enum ReplaceConfirmationChoice {
SUBSTITUTE_THIS,
SUBSTITUTE_LAST,
SKIP,
QUIT,
SUBSTITUTE_ALL,
}
public enum SearchOptions {
BACKWARDS,
WANT_ENDPOS,
WRAP,
SHOW_MESSAGES,
WHOLE_FILE,
IGNORE_SMARTCASE,
}
private @Nullable String lastSearch;
private @Nullable String lastPattern;
private @Nullable String lastSubstitute;
private @Nullable String lastReplace;
private @Nullable String lastOffset;
private boolean lastIgnoreSmartCase;
private @NotNull Direction lastDir = Direction.FORWARDS;
private boolean showSearchHighlight = OptionsManager.INSTANCE.getHlsearch().isSet();
private boolean do_all = false; /* do multiple substitutions per line */
private boolean do_ask = false; /* ask for confirmation */
private boolean do_error = true; /* if false, ignore errors */
//private boolean do_print = false; /* print last line with subs. */
private char do_ic = 0; /* ignore case flag */
private static final int RE_LAST = 1;
private static final int RE_SEARCH = 2;
private static final int RE_SUBST = 3;
private static final Logger logger = Logger.getInstance(SearchGroup.class.getName());
}
| src/com/maddyhome/idea/vim/group/SearchGroup.java | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2020 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.group;
import com.google.common.collect.Lists;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.RoamingType;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.markup.*;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.Ref;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.CommandFlags;
import com.maddyhome.idea.vim.common.CharacterPosition;
import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.ex.ranges.LineRange;
import com.maddyhome.idea.vim.helper.*;
import com.maddyhome.idea.vim.option.ListOption;
import com.maddyhome.idea.vim.option.OptionChangeListener;
import com.maddyhome.idea.vim.option.OptionsManager;
import com.maddyhome.idea.vim.regexp.CharPointer;
import com.maddyhome.idea.vim.regexp.CharacterClasses;
import com.maddyhome.idea.vim.regexp.RegExp;
import com.maddyhome.idea.vim.ui.ModalEntry;
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel;
import kotlin.jvm.functions.Function1;
import org.jdom.Element;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import static com.maddyhome.idea.vim.helper.SearchHelperKtKt.shouldIgnoreCase;
@State(name = "VimSearchSettings", storages = {
@Storage(value = "$APP_CONFIG$/vim_settings_local.xml", roamingType = RoamingType.DISABLED)
})
public class SearchGroup implements PersistentStateComponent<Element> {
public SearchGroup() {
final OptionsManager options = OptionsManager.INSTANCE;
options.getHlsearch().addOptionChangeListener((oldValue, newValue) -> {
resetShowSearchHighlight();
forceUpdateSearchHighlights();
});
final OptionChangeListener<Boolean> updateHighlightsIfVisible = (oldValue, newValue) -> {
if (showSearchHighlight) {
forceUpdateSearchHighlights();
}
};
options.getIgnorecase().addOptionChangeListener(updateHighlightsIfVisible);
options.getSmartcase().addOptionChangeListener(updateHighlightsIfVisible);
}
public void turnOn() {
updateSearchHighlights();
}
public void turnOff() {
final boolean show = showSearchHighlight;
clearSearchHighlight();
showSearchHighlight = show;
}
public @Nullable String getLastSearch() {
return lastSearch;
}
// This method is used in AceJump integration plugin
@SuppressWarnings("unused")
public int getLastDir() {
return lastDir.toInt();
}
public @Nullable String getLastPattern() {
return lastPattern;
}
public void resetState() {
lastSearch = lastPattern = lastSubstitute = lastReplace = lastOffset = null;
lastIgnoreSmartCase = false;
lastDir = Direction.UNSET;
resetShowSearchHighlight();
}
private void setLastPattern(@NotNull String lastPattern) {
this.lastPattern = lastPattern;
VimPlugin.getRegister().storeTextSpecial(RegisterGroup.LAST_SEARCH_REGISTER, lastPattern);
VimPlugin.getHistory().addEntry(HistoryGroup.SEARCH, lastPattern);
}
// This method should not be private because it's used in external plugins
@SuppressWarnings("WeakerAccess")
public static @NotNull List<TextRange> findAll(@NotNull Editor editor,
@NotNull String pattern,
int startLine,
int endLine,
boolean ignoreCase) {
final List<TextRange> results = Lists.newArrayList();
final int lineCount = EditorHelper.getLineCount(editor);
final int actualEndLine = endLine == -1 ? lineCount : endLine;
final RegExp.regmmatch_T regMatch = new RegExp.regmmatch_T();
final RegExp regExp = new RegExp();
regMatch.regprog = regExp.vim_regcomp(pattern, 1);
if (regMatch.regprog == null) {
return results;
}
regMatch.rmm_ic = ignoreCase;
int col = 0;
for (int line = startLine; line <= actualEndLine; ) {
int matchedLines = regExp.vim_regexec_multi(regMatch, editor, lineCount, line, col);
if (matchedLines > 0) {
final CharacterPosition startPos = new CharacterPosition(line + regMatch.startpos[0].lnum,
regMatch.startpos[0].col);
final CharacterPosition endPos = new CharacterPosition(line + regMatch.endpos[0].lnum,
regMatch.endpos[0].col);
int start = startPos.toOffset(editor);
int end = endPos.toOffset(editor);
results.add(new TextRange(start, end));
if (start != end) {
line += matchedLines - 1;
col = endPos.column;
}
else {
line += matchedLines;
col = 0;
}
}
else {
line++;
col = 0;
}
}
return results;
}
private static @NotNull ReplaceConfirmationChoice confirmChoice(@NotNull Editor editor, @NotNull String match, @NotNull Caret caret, int startoff) {
final Ref<ReplaceConfirmationChoice> result = Ref.create(ReplaceConfirmationChoice.QUIT);
final Function1<KeyStroke, Boolean> keyStrokeProcessor = key -> {
final ReplaceConfirmationChoice choice;
final char c = key.getKeyChar();
if (StringHelper.isCloseKeyStroke(key) || c == 'q') {
choice = ReplaceConfirmationChoice.QUIT;
} else if (c == 'y') {
choice = ReplaceConfirmationChoice.SUBSTITUTE_THIS;
} else if (c == 'l') {
choice = ReplaceConfirmationChoice.SUBSTITUTE_LAST;
} else if (c == 'n') {
choice = ReplaceConfirmationChoice.SKIP;
} else if (c == 'a') {
choice = ReplaceConfirmationChoice.SUBSTITUTE_ALL;
} else {
return true;
}
result.set(choice);
return false;
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
MotionGroup.moveCaret(editor, caret, startoff);
final TestInputModel inputModel = TestInputModel.getInstance(editor);
for (KeyStroke key = inputModel.nextKeyStroke(); key != null; key = inputModel.nextKeyStroke()) {
if (!keyStrokeProcessor.invoke(key)) {
break;
}
}
}
else {
// XXX: The Ex entry panel is used only for UI here, its logic might be inappropriate for this method
final ExEntryPanel exEntryPanel = ExEntryPanel.getInstanceWithoutShortcuts();
exEntryPanel.activate(editor, new EditorDataContext(editor, null), MessageHelper.message("replace.with.0", match), "", 1);
MotionGroup.moveCaret(editor, caret, startoff);
ModalEntry.INSTANCE.activate(keyStrokeProcessor);
exEntryPanel.deactivate(true, false);
}
return result.get();
}
public int search(@NotNull Editor editor, @NotNull String command, int count, EnumSet<CommandFlags> flags, boolean moveCursor) {
return search(editor, editor.getCaretModel().getPrimaryCaret(), command, count, flags, moveCursor);
}
public int search(@NotNull Editor editor, @NotNull Caret caret, @NotNull String command, int count, EnumSet<CommandFlags> flags,
boolean moveCursor) {
final int res = search(editor, command, caret.getOffset(), count, flags);
if (res != -1 && moveCursor) {
VimPlugin.getMark().saveJumpLocation(editor);
MotionGroup.moveCaret(editor, caret, res);
}
return res;
}
public int search(@NotNull Editor editor, @NotNull String command, int startOffset, int count, @NotNull EnumSet<CommandFlags> flags) {
Direction dir = Direction.FORWARDS;
char type = '/';
String pattern = lastSearch;
String offset = lastOffset;
if (flags.contains(CommandFlags.FLAG_SEARCH_REV)) {
dir = Direction.BACKWARDS;
type = '?';
}
if (command.length() > 0) {
if (command.charAt(0) != type) {
CharPointer p = new CharPointer(command);
CharPointer end = RegExp.skip_regexp(p.ref(0), type, true);
pattern = p.substring(end.pointer() - p.pointer());
if (logger.isDebugEnabled()) logger.debug("pattern=" + pattern);
if (p.charAt() != type) {
if (end.charAt() == type) {
end.inc();
offset = end.toString();
} else {
logger.debug("no offset");
offset = "";
}
}
else {
p.inc();
offset = p.toString();
if (logger.isDebugEnabled()) logger.debug("offset=" + offset);
}
}
else if (command.length() == 1) {
offset = "";
}
else {
offset = command.substring(1);
if (logger.isDebugEnabled()) logger.debug("offset=" + offset);
}
}
lastSearch = pattern;
lastIgnoreSmartCase = false;
if (pattern != null) {
setLastPattern(pattern);
}
lastOffset = offset;
lastDir = dir;
if (logger.isDebugEnabled()) {
logger.debug("lastSearch=" + lastSearch);
logger.debug("lastOffset=" + lastOffset);
logger.debug("lastDir=" + lastDir);
}
resetShowSearchHighlight();
forceUpdateSearchHighlights();
return findItOffset(editor, startOffset, count, lastDir);
}
public int searchWord(@NotNull Editor editor, @NotNull Caret caret, int count, boolean whole, Direction dir) {
TextRange range = SearchHelper.findWordUnderCursor(editor, caret);
if (range == null) {
logger.warn("No range was found");
return -1;
}
StringBuilder pattern = new StringBuilder();
if (whole) {
pattern.append("\\<");
}
pattern.append(EditorHelper.getText(editor, range.getStartOffset(), range.getEndOffset()));
if (whole) {
pattern.append("\\>");
}
MotionGroup.moveCaret(editor, caret, range.getStartOffset());
lastSearch = pattern.toString();
lastIgnoreSmartCase = true;
setLastPattern(lastSearch);
lastOffset = "";
lastDir = dir;
resetShowSearchHighlight();
forceUpdateSearchHighlights();
return findItOffset(editor, caret.getOffset(), count, lastDir);
}
public int searchNext(@NotNull Editor editor, @NotNull Caret caret, int count) {
return searchNextWithDirection(editor, caret, count, lastDir);
}
public int searchPrevious(@NotNull Editor editor, @NotNull Caret caret, int count) {
return searchNextWithDirection(editor, caret, count, lastDir.reverse());
}
public int searchNextFromOffset(@NotNull Editor editor, int offset, int count) {
resetShowSearchHighlight();
updateSearchHighlights();
return findItOffset(editor, offset, count, Direction.FORWARDS);
}
private int searchNextWithDirection(@NotNull Editor editor, @NotNull Caret caret, int count, Direction dir) {
resetShowSearchHighlight();
updateSearchHighlights();
final int startOffset = caret.getOffset();
int offset = findItOffset(editor, startOffset, count, dir);
if (offset == startOffset) {
/* Avoid getting stuck on the current cursor position, which can
* happen when an offset is given and the cursor is on the last char
* in the buffer: Repeat with count + 1. */
offset = findItOffset(editor, startOffset, count + 1, dir);
}
return offset;
}
private void resetShowSearchHighlight() {
showSearchHighlight = OptionsManager.INSTANCE.getHlsearch().isSet();
}
public void clearSearchHighlight() {
showSearchHighlight = false;
updateSearchHighlights();
}
private void forceUpdateSearchHighlights() {
SearchHighlightsHelper.updateSearchHighlights(lastSearch, lastIgnoreSmartCase, showSearchHighlight, true);
}
private void updateSearchHighlights() {
SearchHighlightsHelper.updateSearchHighlights(lastSearch, lastIgnoreSmartCase, showSearchHighlight, false);
}
public void resetIncsearchHighlights() {
SearchHighlightsHelper.updateSearchHighlights(lastSearch, lastIgnoreSmartCase, showSearchHighlight, true);
}
private void highlightSearchLines(@NotNull Editor editor, int startLine, int endLine) {
if (lastSearch != null) {
final List<TextRange> results = findAll(editor, lastSearch, startLine, endLine,
shouldIgnoreCase(lastSearch, lastIgnoreSmartCase));
SearchHighlightsHelper.highlightSearchResults(editor, lastSearch, results, -1);
}
}
public @Nullable TextRange getNextSearchRange(@NotNull Editor editor, int count, boolean forwards) {
editor.getCaretModel().removeSecondaryCarets();
TextRange current = findUnderCaret(editor);
if (current == null || CommandStateHelper.inVisualMode(editor) && atEdgeOfGnRange(current, editor, forwards)) {
current = findNextSearchForGn(editor, count, forwards);
}
else if (count > 1) {
current = findNextSearchForGn(editor, count - 1, forwards);
}
return current;
}
private boolean atEdgeOfGnRange(@NotNull TextRange nextRange, @NotNull Editor editor, boolean forwards) {
int currentPosition = editor.getCaretModel().getOffset();
if (forwards) {
return nextRange.getEndOffset() - VimPlugin.getVisualMotion().getSelectionAdj() == currentPosition;
}
else {
return nextRange.getStartOffset() == currentPosition;
}
}
private @Nullable TextRange findNextSearchForGn(@NotNull Editor editor, int count, boolean forwards) {
if (forwards) {
final EnumSet<SearchOptions> searchOptions = EnumSet.of(SearchOptions.WRAP, SearchOptions.WHOLE_FILE);
return findIt(editor, lastSearch, editor.getCaretModel().getOffset(), count, searchOptions);
} else {
return searchBackward(editor, editor.getCaretModel().getOffset(), count);
}
}
private @Nullable TextRange findUnderCaret(@NotNull Editor editor) {
final TextRange backSearch = searchBackward(editor, editor.getCaretModel().getOffset() + 1, 1);
if (backSearch == null) return null;
return backSearch.contains(editor.getCaretModel().getOffset()) ? backSearch : null;
}
private @Nullable TextRange searchBackward(@NotNull Editor editor, int offset, int count) {
// Backward search returns wrongs end offset for some cases. That's why we should perform additional forward search
final EnumSet<SearchOptions> searchOptions = EnumSet.of(SearchOptions.WRAP, SearchOptions.WHOLE_FILE, SearchOptions.BACKWARDS);
final TextRange foundBackward = findIt(editor, lastSearch, offset, count, searchOptions);
if (foundBackward == null) return null;
int startOffset = foundBackward.getStartOffset() - 1;
if (startOffset < 0) startOffset = EditorHelperRt.getFileSize(editor);
searchOptions.remove(SearchOptions.BACKWARDS);
return findIt(editor, lastSearch, startOffset, 1, searchOptions);
}
public static TextRange findIt(@NotNull Editor editor, @Nullable String pattern, int startOffset, int count, EnumSet<SearchOptions> searchOptions) {
if (pattern == null || pattern.length() == 0) {
logger.warn("Pattern is null or empty. Cannot perform search");
return null;
}
Direction dir = searchOptions.contains(SearchOptions.BACKWARDS) ? Direction.BACKWARDS : Direction.FORWARDS;
//RE sp;
RegExp sp;
RegExp.regmmatch_T regmatch = new RegExp.regmmatch_T();
regmatch.rmm_ic = shouldIgnoreCase(pattern, searchOptions.contains(SearchOptions.IGNORE_SMARTCASE));
sp = new RegExp();
regmatch.regprog = sp.vim_regcomp(pattern, 1);
if (regmatch.regprog == null) {
if (logger.isDebugEnabled()) logger.debug("bad pattern: " + pattern);
return null;
}
/*
int extra_col = 1;
int startcol = -1;
boolean found = false;
boolean match_ok = true;
LogicalPosition pos = editor.offsetToLogicalPosition(startOffset);
LogicalPosition endpos = null;
//REMatch match = null;
*/
CharacterPosition lpos = CharacterPosition.Companion.fromOffset(editor, startOffset);
RegExp.lpos_T pos = new RegExp.lpos_T();
pos.lnum = lpos.line;
pos.col = lpos.column;
int found;
int lnum; /* no init to shut up Apollo cc */
//RegExp.regmmatch_T regmatch;
CharPointer ptr;
int matchcol;
RegExp.lpos_T matchpos;
RegExp.lpos_T endpos = new RegExp.lpos_T();
int loop;
RegExp.lpos_T start_pos;
boolean at_first_line;
int extra_col = dir == Direction.FORWARDS ? 1 : 0;
boolean match_ok;
long nmatched;
//int submatch = 0;
boolean first_match = true;
int lineCount = EditorHelper.getLineCount(editor);
int startLine = 0;
int endLine = lineCount;
do /* loop for count */ {
start_pos = new RegExp.lpos_T(pos); /* remember start pos for detecting no match */
found = 0; /* default: not found */
at_first_line = true; /* default: start in first line */
if (pos.lnum == -1) /* correct lnum for when starting in line 0 */ {
pos.lnum = 0;
pos.col = 0;
at_first_line = false; /* not in first line now */
}
/*
* Start searching in current line, unless searching backwards and
* we're in column 0.
*/
if (dir == Direction.BACKWARDS && start_pos.col == 0) {
lnum = pos.lnum - 1;
at_first_line = false;
}
else {
lnum = pos.lnum;
}
int lcount = EditorHelper.getLineCount(editor);
for (loop = 0; loop <= 1; ++loop) /* loop twice if 'wrapscan' set */ {
if (!searchOptions.contains(SearchOptions.WHOLE_FILE)) {
startLine = lnum;
endLine = lnum + 1;
}
for (; lnum >= startLine && lnum < endLine; lnum += dir.toInt(), at_first_line = false) {
/*
* Look for a match somewhere in the line.
*/
nmatched = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, 0);
if (nmatched > 0) {
/* match may actually be in another line when using \zs */
matchpos = new RegExp.lpos_T(regmatch.startpos[0]);
endpos = new RegExp.lpos_T(regmatch.endpos[0]);
ptr = new CharPointer(EditorHelper.getLineBuffer(editor, lnum + matchpos.lnum));
/*
* Forward search in the first line: match should be after
* the start position. If not, continue at the end of the
* match (this is vi compatible) or on the next char.
*/
if (dir == Direction.FORWARDS && at_first_line) {
match_ok = true;
/*
* When match lands on a NUL the cursor will be put
* one back afterwards, compare with that position,
* otherwise "/$" will get stuck on end of line.
*/
while (matchpos.lnum == 0
&& (searchOptions.contains(SearchOptions.WANT_ENDPOS) && first_match
? (nmatched == 1 && endpos.col - 1 < start_pos.col + extra_col)
: (matchpos.col - (ptr.charAt(matchpos.col) == '\u0000' ? 1 : 0) < start_pos.col + extra_col))) {
if (nmatched > 1) {
/* end is in next line, thus no match in
* this line */
match_ok = false;
break;
}
matchcol = endpos.col;
/* for empty match: advance one char */
if (matchcol == matchpos.col && ptr.charAt(matchcol) != '\u0000') {
++matchcol;
}
if (ptr.charAt(matchcol) == '\u0000' ||
(nmatched = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, matchcol)) == 0) {
match_ok = false;
break;
}
matchpos = new RegExp.lpos_T(regmatch.startpos[0]);
endpos = new RegExp.lpos_T(regmatch.endpos[0]);
/* Need to get the line pointer again, a
* multi-line search may have made it invalid. */
ptr = new CharPointer(EditorHelper.getLineBuffer(editor, lnum));
}
if (!match_ok) {
continue;
}
}
if (dir == Direction.BACKWARDS) {
/*
* Now, if there are multiple matches on this line,
* we have to get the last one. Or the last one before
* the cursor, if we're on that line.
* When putting the new cursor at the end, compare
* relative to the end of the match.
*/
match_ok = false;
for (;;) {
if (loop != 0 ||
(searchOptions.contains(SearchOptions.WANT_ENDPOS)
? (lnum + regmatch.endpos[0].lnum < start_pos.lnum || (lnum + regmatch.endpos[0].lnum == start_pos.lnum && regmatch.endpos[0].col - 1 < start_pos.col + extra_col))
: (lnum + regmatch.startpos[0].lnum < start_pos.lnum || (lnum + regmatch.startpos[0].lnum == start_pos.lnum && regmatch.startpos[0].col < start_pos.col + extra_col)))) {
/* Remember this position, we use it if it's
* the last match in the line. */
match_ok = true;
matchpos = new RegExp.lpos_T(regmatch.startpos[0]);
endpos = new RegExp.lpos_T(regmatch.endpos[0]);
}
else {
break;
}
/*
* We found a valid match, now check if there is
* another one after it.
* If vi-compatible searching, continue at the end
* of the match, otherwise continue one position
* forward.
*/
if (nmatched > 1) {
break;
}
matchcol = endpos.col;
/* for empty match: advance one char */
if (matchcol == matchpos.col && ptr.charAt(matchcol) != '\u0000') {
++matchcol;
}
if (ptr.charAt(matchcol) == '\u0000' ||
(nmatched = sp.vim_regexec_multi(regmatch, editor, lcount, lnum + matchpos.lnum, matchcol)) == 0) {
break;
}
/* Need to get the line pointer again, a
* multi-line search may have made it invalid. */
ptr = new CharPointer(EditorHelper.getLineBuffer(editor, lnum + matchpos.lnum));
}
/*
* If there is only a match after the cursor, skip
* this match.
*/
if (!match_ok) {
continue;
}
}
pos.lnum = lnum + matchpos.lnum;
pos.col = matchpos.col;
endpos.lnum = lnum + endpos.lnum;
found = 1;
first_match = false;
/* Set variables used for 'incsearch' highlighting. */
//search_match_lines = endpos.lnum - (lnum - first_lnum);
//search_match_endcol = endpos.col;
break;
}
//line_breakcheck(); /* stop if ctrl-C typed */
//if (got_int)
// break;
if (loop != 0 && lnum == start_pos.lnum) {
break; /* if second loop, stop where started */
}
}
at_first_line = false;
/*
* stop the search if wrapscan isn't set, after an interrupt and
* after a match
*/
if (!searchOptions.contains(SearchOptions.WRAP) || found != 0) {
break;
}
/*
* If 'wrapscan' is set we continue at the other end of the file.
* If 'shortmess' does not contain 's', we give a message.
* This message is also remembered in keep_msg for when the screen
* is redrawn. The keep_msg is cleared whenever another message is
* written.
*/
if (dir == Direction.BACKWARDS) /* start second loop at the other end */ {
lnum = lineCount - 1;
//if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG))
// give_warning((char_u *)_(top_bot_msg), TRUE);
}
else {
lnum = 0;
//if (!shortmess(SHM_SEARCH) && (options & SEARCH_MSG))
// give_warning((char_u *)_(bot_top_msg), TRUE);
}
}
//if (got_int || called_emsg || break_loop)
// break;
}
while (--count > 0 && found != 0); /* stop after count matches or no match */
if (found == 0) /* did not find it */ {
//if ((options & SEARCH_MSG) == SEARCH_MSG)
if (searchOptions.contains(SearchOptions.SHOW_MESSAGES)) {
if (searchOptions.contains(SearchOptions.WRAP)) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern));
}
else if (lnum <= 0) {
VimPlugin.showMessage(MessageHelper.message(Msg.E384, pattern));
}
else {
VimPlugin.showMessage(MessageHelper.message(Msg.E385, pattern));
}
}
return null;
}
//return new TextRange(editor.logicalPositionToOffset(new LogicalPosition(pos.lnum, pos.col)),
// editor.logicalPositionToOffset(new LogicalPosition(endpos.lnum, endpos.col)));
//return new TextRange(editor.logicalPositionToOffset(new LogicalPosition(pos.lnum, 0)) + pos.col,
// editor.logicalPositionToOffset(new LogicalPosition(endpos.lnum, 0)) + endpos.col);
return new TextRange(new CharacterPosition(pos.lnum, pos.col).toOffset(editor),
new CharacterPosition(endpos.lnum, endpos.col).toOffset(editor));
}
private int findItOffset(@NotNull Editor editor, int startOffset, int count, Direction dir) {
boolean wrap = OptionsManager.INSTANCE.getWrapscan().isSet();
logger.debug("Perform search. Direction: " + dir + " wrap: " + wrap);
int offset = 0;
boolean offsetIsLineOffset = false;
boolean hasEndOffset = false;
ParsePosition pp = new ParsePosition(0);
if (lastOffset == null) {
logger.warn("Last offset is null. Cannot perform search");
return -1;
}
if (lastOffset.length() > 0) {
if (Character.isDigit(lastOffset.charAt(0)) || lastOffset.charAt(0) == '+' || lastOffset.charAt(0) == '-') {
offsetIsLineOffset = true;
if (lastOffset.equals("+")) {
offset = 1;
} else if (lastOffset.equals("-")) {
offset = -1;
} else {
if (lastOffset.charAt(0) == '+') {
lastOffset = lastOffset.substring(1);
}
NumberFormat nf = NumberFormat.getIntegerInstance();
pp = new ParsePosition(0);
Number num = nf.parse(lastOffset, pp);
if (num != null) {
offset = num.intValue();
}
}
} else if ("ebs".indexOf(lastOffset.charAt(0)) != -1) {
if (lastOffset.length() >= 2) {
if ("+-".indexOf(lastOffset.charAt(1)) != -1) {
offset = 1;
}
NumberFormat nf = NumberFormat.getIntegerInstance();
pp = new ParsePosition(lastOffset.charAt(1) == '+' ? 2 : 1);
Number num = nf.parse(lastOffset, pp);
if (num != null) {
offset = num.intValue();
}
}
hasEndOffset = lastOffset.charAt(0) == 'e';
}
}
/*
* If there is a character offset, subtract it from the current
* position, so we don't get stuck at "?pat?e+2" or "/pat/s-2".
* Skip this if pos.col is near MAXCOL (closed fold).
* This is not done for a line offset, because then we would not be vi
* compatible.
*/
if (!offsetIsLineOffset && offset != 0) {
startOffset = Math.max(0, Math.min(startOffset - offset, EditorHelperRt.getFileSize(editor) - 1));
}
EnumSet<SearchOptions> searchOptions = EnumSet.of(SearchOptions.SHOW_MESSAGES, SearchOptions.WHOLE_FILE);
if (dir == Direction.BACKWARDS) searchOptions.add(SearchOptions.BACKWARDS);
if (lastIgnoreSmartCase) searchOptions.add(SearchOptions.IGNORE_SMARTCASE);
if (wrap) searchOptions.add(SearchOptions.WRAP);
if (hasEndOffset) searchOptions.add(SearchOptions.WANT_ENDPOS);
TextRange range = findIt(editor, lastSearch, startOffset, count, searchOptions);
if (range == null) {
logger.warn("No range is found");
return -1;
}
int res = range.getStartOffset();
if (offsetIsLineOffset) {
int line = editor.offsetToLogicalPosition(range.getStartOffset()).line;
int newLine = EditorHelper.normalizeLine(editor, line + offset);
res = VimPlugin.getMotion().moveCaretToLineStart(editor, newLine);
}
else if (hasEndOffset || offset != 0) {
int base = hasEndOffset ? range.getEndOffset() - 1 : range.getStartOffset();
res = Math.max(0, Math.min(base + offset, EditorHelperRt.getFileSize(editor) - 1));
}
int ppos = pp.getIndex();
if (ppos < lastOffset.length() - 1 && lastOffset.charAt(ppos) == ';') {
EnumSet<CommandFlags> flags = EnumSet.noneOf(CommandFlags.class);
if (lastOffset.charAt(ppos + 1) == '/') {
flags.add(CommandFlags.FLAG_SEARCH_FWD);
}
else if (lastOffset.charAt(ppos + 1) == '?') {
flags.add(CommandFlags.FLAG_SEARCH_REV);
}
else {
return res;
}
if (lastOffset.length() - ppos > 2) {
ppos++;
}
res = search(editor, lastOffset.substring(ppos + 1), res, 1, flags);
}
return res;
}
@RWLockLabel.SelfSynchronized
public boolean searchAndReplace(@NotNull Editor editor, @NotNull Caret caret, @NotNull LineRange range,
@NotNull @NonNls String excmd, @NonNls String exarg) {
// Explicitly exit visual mode here, so that visual mode marks don't change when we move the cursor to a match.
if (CommandStateHelper.inVisualMode(editor)) {
ModeHelper.exitVisualMode(editor);
}
CharPointer cmd = new CharPointer(new StringBuffer(exarg));
int which_pat;
if ("~".equals(excmd)) {
which_pat = RE_LAST; /* use last used regexp */
}
else {
which_pat = RE_SUBST; /* use last substitute regexp */
}
CharPointer pat;
CharPointer sub;
char delimiter;
/* new pattern and substitution */
if (excmd.charAt(0) == 's' && !cmd.isNul() && !Character.isWhitespace(
cmd.charAt()) && "0123456789cegriIp|\"".indexOf(cmd.charAt()) == -1) {
/* don't accept alphanumeric for separator */
if (CharacterClasses.isAlpha(cmd.charAt())) {
VimPlugin.showMessage(MessageHelper.message(Msg.E146));
return false;
}
/*
* undocumented vi feature:
* "\/sub/" and "\?sub?" use last used search pattern (almost like
* //sub/r). "\&sub&" use last substitute pattern (like //sub/).
*/
if (cmd.charAt() == '\\') {
cmd.inc();
if ("/?&".indexOf(cmd.charAt()) == -1) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_backslash));
return false;
}
if (cmd.charAt() != '&') {
which_pat = RE_SEARCH; /* use last '/' pattern */
}
pat = new CharPointer(""); /* empty search pattern */
delimiter = cmd.charAt(); /* remember delimiter character */
cmd.inc();
}
else {
/* find the end of the regexp */
which_pat = RE_LAST; /* use last used regexp */
delimiter = cmd.charAt(); /* remember delimiter character */
cmd.inc();
pat = cmd.ref(0); /* remember start of search pat */
cmd = RegExp.skip_regexp(cmd, delimiter, true);
if (cmd.charAt() == delimiter) /* end delimiter found */ {
cmd.set('\u0000').inc(); /* replace it with a NUL */
}
}
/*
* Small incompatibility: vi sees '\n' as end of the command, but in
* Vim we want to use '\n' to find/substitute a NUL.
*/
sub = cmd.ref(0); /* remember the start of the substitution */
while (!cmd.isNul()) {
if (cmd.charAt() == delimiter) /* end delimiter found */ {
cmd.set('\u0000').inc(); /* replace it with a NUL */
break;
}
if (cmd.charAt(0) == '\\' && cmd.charAt(1) != 0) /* skip escaped characters */ {
cmd.inc();
}
cmd.inc();
}
}
else {
/* use previous pattern and substitution */
if (lastReplace == null) {
/* there is no previous command */
VimPlugin.showMessage(MessageHelper.message(Msg.e_nopresub));
return false;
}
pat = null; /* search_regcomp() will use previous pattern */
sub = new CharPointer(lastReplace);
}
/*
* Find trailing options. When '&' is used, keep old options.
*/
if (cmd.charAt() == '&') {
cmd.inc();
}
else {
do_all = OptionsManager.INSTANCE.getGdefault().isSet();
do_ask = false;
do_error = true;
do_ic = 0;
}
while (!cmd.isNul()) {
/*
* Note that 'g' and 'c' are always inverted, also when p_ed is off.
* 'r' is never inverted.
*/
if (cmd.charAt() == 'g') {
do_all = !do_all;
}
else if (cmd.charAt() == 'c') {
do_ask = !do_ask;
}
else if (cmd.charAt() == 'e') {
do_error = !do_error;
}
else if (cmd.charAt() == 'r') {
/* use last used regexp */
which_pat = RE_LAST;
}
else if (cmd.charAt() == 'i') {
/* ignore case */
do_ic = 'i';
}
else if (cmd.charAt() == 'I') {
/* don't ignore case */
do_ic = 'I';
}
else if (cmd.charAt() != 'p') {
break;
}
cmd.inc();
}
int line1 = range.startLine;
int line2 = range.endLine;
if (line1 < 0 || line2 < 0) {
return false;
}
/*
* check for a trailing count
*/
cmd.skipWhitespaces();
if (Character.isDigit(cmd.charAt())) {
int i = cmd.getDigits();
if (i <= 0 && do_error) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_zerocount));
return false;
}
line1 = line2;
line2 = EditorHelper.normalizeLine(editor, line1 + i - 1);
}
/*
* check for trailing command or garbage
*/
cmd.skipWhitespaces();
if (!cmd.isNul() && cmd.charAt() != '"') {
/* if not end-of-line or comment */
VimPlugin.showMessage(MessageHelper.message(Msg.e_trailing));
return false;
}
String pattern = "";
if (pat == null || pat.isNul()) {
switch (which_pat) {
case RE_LAST:
pattern = lastPattern;
break;
case RE_SEARCH:
pattern = lastSearch;
break;
case RE_SUBST:
pattern = lastSubstitute;
break;
}
}
else {
pattern = pat.toString();
}
lastSubstitute = pattern;
lastSearch = pattern;
if (pattern != null) {
setLastPattern(pattern);
}
int start = editor.getDocument().getLineStartOffset(line1);
int end = editor.getDocument().getLineEndOffset(line2);
RegExp sp;
RegExp.regmmatch_T regmatch = new RegExp.regmmatch_T();
sp = new RegExp();
regmatch.regprog = sp.vim_regcomp(pattern, 1);
if (regmatch.regprog == null) {
if (do_error) {
VimPlugin.showMessage(MessageHelper.message(Msg.e_invcmd));
}
return false;
}
/* the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase' */
regmatch.rmm_ic = shouldIgnoreCase(pattern != null ? pattern : "", false);
if (do_ic == 'i') {
regmatch.rmm_ic = true;
}
else if (do_ic == 'I') {
regmatch.rmm_ic = false;
}
/*
* ~ in the substitute pattern is replaced with the old pattern.
* We do it here once to avoid it to be replaced over and over again.
* But don't do it when it starts with "\=", then it's an expression.
*/
if (!(sub.charAt(0) == '\\' && sub.charAt(1) == '=') && lastReplace != null) {
StringBuffer tmp = new StringBuffer(sub.toString());
int pos = 0;
while ((pos = tmp.indexOf("~", pos)) != -1) {
if (pos == 0 || tmp.charAt(pos - 1) != '\\') {
tmp.replace(pos, pos + 1, lastReplace);
pos += lastReplace.length();
}
pos++;
}
sub = new CharPointer(tmp);
}
lastReplace = sub.toString();
resetShowSearchHighlight();
forceUpdateSearchHighlights();
if (logger.isDebugEnabled()) {
logger.debug("search range=[" + start + "," + end + "]");
logger.debug("pattern=" + pattern + ", replace=" + sub);
}
int lastMatch = -1;
int lastLine = -1;
int searchcol = 0;
boolean firstMatch = true;
boolean got_quit = false;
int lcount = EditorHelper.getLineCount(editor);
for (int lnum = line1; lnum <= line2 && !got_quit; ) {
CharacterPosition newpos = null;
int nmatch = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, searchcol);
if (nmatch > 0) {
if (firstMatch) {
VimPlugin.getMark().saveJumpLocation(editor);
firstMatch = false;
}
String match = sp.vim_regsub_multi(regmatch, lnum, sub, 1, false);
if (match == null) {
return false;
}
int line = lnum + regmatch.startpos[0].lnum;
CharacterPosition startpos = new CharacterPosition(lnum + regmatch.startpos[0].lnum, regmatch.startpos[0].col);
CharacterPosition endpos = new CharacterPosition(lnum + regmatch.endpos[0].lnum, regmatch.endpos[0].col);
int startoff = startpos.toOffset(editor);
int endoff = endpos.toOffset(editor);
int newend = startoff + match.length();
if (do_all || line != lastLine) {
boolean doReplace = true;
if (do_ask) {
RangeHighlighter hl = SearchHighlightsHelper.addSubstitutionConfirmationHighlight(editor, startoff, endoff);
final ReplaceConfirmationChoice choice = confirmChoice(editor, match, caret, startoff);
editor.getMarkupModel().removeHighlighter(hl);
switch (choice) {
case SUBSTITUTE_THIS:
doReplace = true;
break;
case SKIP:
doReplace = false;
break;
case SUBSTITUTE_ALL:
do_ask = false;
break;
case QUIT:
doReplace = false;
got_quit = true;
break;
case SUBSTITUTE_LAST:
do_all = false;
line2 = lnum;
doReplace = true;
break;
}
}
if (doReplace) {
ApplicationManager.getApplication().runWriteAction(() -> editor.getDocument().replaceString(startoff, endoff, match));
lastMatch = startoff;
newpos = CharacterPosition.Companion.fromOffset(editor, newend);
lnum += newpos.line - endpos.line;
line2 += newpos.line - endpos.line;
}
}
lastLine = line;
lnum += nmatch - 1;
if (do_all && startoff != endoff) {
if (newpos != null) {
lnum = newpos.line;
searchcol = newpos.column;
}
else {
searchcol = endpos.column;
}
}
else {
searchcol = 0;
lnum++;
}
}
else {
lnum++;
searchcol = 0;
}
}
if (lastMatch != -1) {
if (!got_quit) {
MotionGroup.moveCaret(editor, caret,
VimPlugin.getMotion().moveCaretToLineStartSkipLeading(editor, editor.offsetToLogicalPosition(lastMatch).line));
}
}
else {
VimPlugin.showMessage(MessageHelper.message(Msg.e_patnotf2, pattern));
}
return true;
}
public void saveData(@NotNull Element element) {
logger.debug("saveData");
Element search = new Element("search");
if (lastSearch != null) {
search.addContent(createElementWithText("last-search", lastSearch));
}
if (lastOffset != null) {
search.addContent(createElementWithText("last-offset", lastOffset));
}
if (lastPattern != null) {
search.addContent(createElementWithText("last-pattern", lastPattern));
}
if (lastReplace != null) {
search.addContent(createElementWithText("last-replace", lastReplace));
}
if (lastSubstitute != null) {
search.addContent(createElementWithText("last-substitute", lastSubstitute));
}
Element text = new Element("last-dir");
text.addContent(Integer.toString(lastDir.toInt()));
search.addContent(text);
text = new Element("show-last");
text.addContent(Boolean.toString(showSearchHighlight));
if (logger.isDebugEnabled()) logger.debug("text=" + text);
search.addContent(text);
element.addContent(search);
}
private static @NotNull Element createElementWithText(@NotNull String name, @NotNull String text) {
return StringHelper.setSafeXmlText(new Element(name), text);
}
public void readData(@NotNull Element element) {
logger.debug("readData");
Element search = element.getChild("search");
if (search == null) {
return;
}
lastSearch = getSafeChildText(search, "last-search");
lastOffset = getSafeChildText(search, "last-offset");
lastPattern = getSafeChildText(search, "last-pattern");
lastReplace = getSafeChildText(search, "last-replace");
lastSubstitute = getSafeChildText(search, "last-substitute");
Element dir = search.getChild("last-dir");
lastDir = Direction.Companion.fromInt(Integer.parseInt(dir.getText()));
Element show = search.getChild("show-last");
final ListOption vimInfo = OptionsManager.INSTANCE.getViminfo();
final boolean disableHighlight = vimInfo.contains("h");
showSearchHighlight = !disableHighlight && Boolean.parseBoolean(show.getText());
if (logger.isDebugEnabled()) {
logger.debug("show=" + show + "(" + show.getText() + ")");
logger.debug("showSearchHighlight=" + showSearchHighlight);
}
}
private static @Nullable String getSafeChildText(@NotNull Element element, @NotNull String name) {
final Element child = element.getChild(name);
return child != null ? StringHelper.getSafeXmlText(child) : null;
}
/**
* Updates search highlights when the selected editor changes
*/
@SuppressWarnings("unused")
public static void fileEditorManagerSelectionChangedCallback(@NotNull FileEditorManagerEvent event) {
VimPlugin.getSearch().updateSearchHighlights();
}
@Nullable
@Override
public Element getState() {
Element element = new Element("search");
saveData(element);
return element;
}
@Override
public void loadState(@NotNull Element state) {
readData(state);
}
public static class DocumentSearchListener implements DocumentListener {
public static DocumentSearchListener INSTANCE = new DocumentSearchListener();
@Contract(pure = true)
private DocumentSearchListener () {
}
@Override
public void documentChanged(@NotNull DocumentEvent event) {
for (Project project : ProjectManager.getInstance().getOpenProjects()) {
final Document document = event.getDocument();
for (Editor editor : EditorFactory.getInstance().getEditors(document, project)) {
Collection<RangeHighlighter> hls = UserDataManager.getVimLastHighlighters(editor);
if (hls == null) {
continue;
}
if (logger.isDebugEnabled()) {
logger.debug("hls=" + hls);
logger.debug("event=" + event);
}
// We can only re-highlight whole lines, so clear any highlights in the affected lines
final LogicalPosition startPosition = editor.offsetToLogicalPosition(event.getOffset());
final LogicalPosition endPosition = editor.offsetToLogicalPosition(event.getOffset() + event.getNewLength());
final int startLineOffset = document.getLineStartOffset(startPosition.line);
final int endLineOffset = document.getLineEndOffset(endPosition.line);
final Iterator<RangeHighlighter> iter = hls.iterator();
while (iter.hasNext()) {
final RangeHighlighter highlighter = iter.next();
if (!highlighter.isValid() || (highlighter.getStartOffset() >= startLineOffset && highlighter.getEndOffset() <= endLineOffset)) {
iter.remove();
editor.getMarkupModel().removeHighlighter(highlighter);
}
}
VimPlugin.getSearch().highlightSearchLines(editor, startPosition.line, endPosition.line);
if (logger.isDebugEnabled()) {
hls = UserDataManager.getVimLastHighlighters(editor);
logger.debug("sl=" + startPosition.line + ", el=" + endPosition.line);
logger.debug("hls=" + hls);
}
}
}
}
}
private enum ReplaceConfirmationChoice {
SUBSTITUTE_THIS,
SUBSTITUTE_LAST,
SKIP,
QUIT,
SUBSTITUTE_ALL,
}
public enum SearchOptions {
BACKWARDS,
WANT_ENDPOS,
WRAP,
SHOW_MESSAGES,
WHOLE_FILE,
IGNORE_SMARTCASE,
}
private @Nullable String lastSearch;
private @Nullable String lastPattern;
private @Nullable String lastSubstitute;
private @Nullable String lastReplace;
private @Nullable String lastOffset;
private boolean lastIgnoreSmartCase;
private Direction lastDir;
private boolean showSearchHighlight = OptionsManager.INSTANCE.getHlsearch().isSet();
private boolean do_all = false; /* do multiple substitutions per line */
private boolean do_ask = false; /* ask for confirmation */
private boolean do_error = true; /* if false, ignore errors */
//private boolean do_print = false; /* print last line with subs. */
private char do_ic = 0; /* ignore case flag */
private static final int RE_LAST = 1;
private static final int RE_SEARCH = 2;
private static final int RE_SUBST = 3;
private static final Logger logger = Logger.getInstance(SearchGroup.class.getName());
}
| Fix settings saving issues because of NPE
| src/com/maddyhome/idea/vim/group/SearchGroup.java | Fix settings saving issues because of NPE |
|
Java | epl-1.0 | 972c33de81e117aeafa1e730e522ee54b2d00dc1 | 0 | naidu/mercurialeclipse,tectronics/mercurialeclipse,boa0332/mercurialeclipse,leinier/mercurialeclipse | /*******************************************************************************
* Copyright (c) 2008 VecTrace (Zingo Andersen) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Jerome Negre - implementation
* Bastian Doetsch
* StefanC
* Zsolt Koppany (Intland)
* Adam Berkes (Intland)
* Andrei Loskutov - bug fixes
*******************************************************************************/
package com.vectrace.MercurialEclipse.commands;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import com.aragost.javahg.commands.CommitCommand;
import com.aragost.javahg.commands.ExecutionException;
import com.aragost.javahg.commands.flags.CommitCommandFlags;
import com.vectrace.MercurialEclipse.exception.HgException;
import com.vectrace.MercurialEclipse.model.HgRoot;
import com.vectrace.MercurialEclipse.storage.HgCommitMessageManager;
import com.vectrace.MercurialEclipse.team.MercurialUtilities;
import com.vectrace.MercurialEclipse.team.cache.RefreshRootJob;
import com.vectrace.MercurialEclipse.utils.ResourceUtils;
/**
*
*/
public class HgCommitClient extends AbstractClient {
/**
* Commit given resources and refresh the caches for the associated projects
*
* Note: refreshes local and outgoing status
*/
public static void commitResources(List<IResource> resources, String user, String message,
boolean closeBranch, boolean amend, IProgressMonitor monitor) throws HgException {
Map<HgRoot, List<IResource>> resourcesByRoot = ResourceUtils.groupByRoot(resources);
for (Map.Entry<HgRoot, List<IResource>> mapEntry : resourcesByRoot.entrySet()) {
HgRoot root = mapEntry.getKey();
if (monitor != null) {
if (monitor.isCanceled()) {
break;
}
monitor.subTask(Messages.getString("HgCommitClient.commitJob.committing") + root.getName()); //$NON-NLS-1$
}
List<IResource> files = mapEntry.getValue();
commit(root, AbstractClient.toFiles(files), user, message, closeBranch, amend);
}
for (HgRoot root : resourcesByRoot.keySet()) {
new RefreshRootJob(root, RefreshRootJob.LOCAL_AND_OUTGOING).schedule();
}
}
/**
* Commit given hg root with all checked out/added/deleted changes and refresh the caches for
* the associated projects
*
* Note: refreshes local and outgoing status
*/
public static void commitResources(HgRoot root, String user, String message, boolean closeBranch,
boolean amend, IProgressMonitor monitor) throws HgException {
monitor.subTask(Messages.getString("HgCommitClient.commitJob.committing") + root.getName()); //$NON-NLS-1$
List<File> emptyList = Collections.emptyList();
try {
commit(root, emptyList, user, message, closeBranch, amend);
} finally {
new RefreshRootJob(root, RefreshRootJob.LOCAL_AND_OUTGOING).schedule();
}
}
/**
* Performs commit. No refresh of any cashes is done afterwards.
*
* <b>Note</b> clients should not use this method directly, it is NOT private for tests only
*/
protected static void commit(HgRoot hgRoot, List<File> files, String user, String message,
boolean closeBranch, boolean amend) throws HgException {
CommitCommand command = CommitCommandFlags.on(hgRoot.getRepository());
user = MercurialUtilities.getDefaultUserName(user);
command.user(user);
if (closeBranch) {
command.closeBranch();
}
if (amend) {
command.amend();
}
command.message(message);
try {
command.execute(files.toArray(new File[files.size()]));
} catch (ExecutionException e) {
throw new HgException(e.getLocalizedMessage(), e);
}
HgCommitMessageManager.updateDefaultCommitName(hgRoot, user);
}
/**
* Commit given project after the merge and refresh the caches. Implementation note: after
* merge, no files should be specified.
*
* Note: refreshes local and outgoing status
*/
public static void commit(HgRoot hgRoot, String user, String message) {
CommitCommand command = CommitCommandFlags.on(hgRoot.getRepository());
user = MercurialUtilities.getDefaultUserName(user);
command.user(user);
command.message(message);
try {
command.execute();
HgCommitMessageManager.updateDefaultCommitName(hgRoot, user);
} finally {
new RefreshRootJob(hgRoot, RefreshRootJob.LOCAL_AND_OUTGOING).schedule();
}
}
}
| plugin/src/com/vectrace/MercurialEclipse/commands/HgCommitClient.java | /*******************************************************************************
* Copyright (c) 2008 VecTrace (Zingo Andersen) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Jerome Negre - implementation
* Bastian Doetsch
* StefanC
* Zsolt Koppany (Intland)
* Adam Berkes (Intland)
* Andrei Loskutov - bug fixes
*******************************************************************************/
package com.vectrace.MercurialEclipse.commands;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import com.aragost.javahg.commands.CommitCommand;
import com.aragost.javahg.commands.flags.CommitCommandFlags;
import com.vectrace.MercurialEclipse.exception.HgException;
import com.vectrace.MercurialEclipse.model.HgRoot;
import com.vectrace.MercurialEclipse.storage.HgCommitMessageManager;
import com.vectrace.MercurialEclipse.team.MercurialUtilities;
import com.vectrace.MercurialEclipse.team.cache.RefreshRootJob;
import com.vectrace.MercurialEclipse.utils.ResourceUtils;
/**
*
*/
public class HgCommitClient extends AbstractClient {
/**
* Commit given resources and refresh the caches for the associated projects
*
* Note: refreshes local and outgoing status
*/
public static void commitResources(List<IResource> resources, String user, String message,
boolean closeBranch, boolean amend, IProgressMonitor monitor) throws HgException {
Map<HgRoot, List<IResource>> resourcesByRoot = ResourceUtils.groupByRoot(resources);
for (Map.Entry<HgRoot, List<IResource>> mapEntry : resourcesByRoot.entrySet()) {
HgRoot root = mapEntry.getKey();
if (monitor != null) {
if (monitor.isCanceled()) {
break;
}
monitor.subTask(Messages.getString("HgCommitClient.commitJob.committing") + root.getName()); //$NON-NLS-1$
}
List<IResource> files = mapEntry.getValue();
commit(root, AbstractClient.toFiles(files), user, message, closeBranch, amend);
}
for (HgRoot root : resourcesByRoot.keySet()) {
new RefreshRootJob(root, RefreshRootJob.LOCAL_AND_OUTGOING).schedule();
}
}
/**
* Commit given hg root with all checked out/added/deleted changes and refresh the caches for
* the associated projects
*
* Note: refreshes local and outgoing status
*/
public static void commitResources(HgRoot root, String user, String message, boolean closeBranch,
boolean amend, IProgressMonitor monitor) throws HgException {
monitor.subTask(Messages.getString("HgCommitClient.commitJob.committing") + root.getName()); //$NON-NLS-1$
List<File> emptyList = Collections.emptyList();
try {
commit(root, emptyList, user, message, closeBranch, amend);
} finally {
new RefreshRootJob(root, RefreshRootJob.LOCAL_AND_OUTGOING).schedule();
}
}
/**
* Performs commit. No refresh of any cashes is done afterwards.
*
* <b>Note</b> clients should not use this method directly, it is NOT private for tests only
*/
protected static void commit(HgRoot hgRoot, List<File> files, String user, String message,
boolean closeBranch, boolean amend) throws HgException {
CommitCommand command = CommitCommandFlags.on(hgRoot.getRepository());
user = MercurialUtilities.getDefaultUserName(user);
command.user(user);
if (closeBranch) {
command.closeBranch();
}
if (amend) {
command.amend();
}
command.message(message);
command.execute(files.toArray(new File[files.size()]));
HgCommitMessageManager.updateDefaultCommitName(hgRoot, user);
}
/**
* Commit given project after the merge and refresh the caches. Implementation note: after
* merge, no files should be specified.
*
* Note: refreshes local and outgoing status
*/
public static void commit(HgRoot hgRoot, String user, String message) {
CommitCommand command = CommitCommandFlags.on(hgRoot.getRepository());
user = MercurialUtilities.getDefaultUserName(user);
command.user(user);
command.message(message);
try {
command.execute();
HgCommitMessageManager.updateDefaultCommitName(hgRoot, user);
} finally {
new RefreshRootJob(hgRoot, RefreshRootJob.LOCAL_AND_OUTGOING).schedule();
}
}
}
| Commit dialog: Fix missing error message
| plugin/src/com/vectrace/MercurialEclipse/commands/HgCommitClient.java | Commit dialog: Fix missing error message |
|
Java | agpl-3.0 | 033c2252c8c5d2ed292864e9591b73c44310f84a | 0 | SamarkandTour/Samapp-mobile,SamarkandTour/Samapp-mobile | package uz.samtuit.sammap.samapp;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class HotelsActivity extends Activity {
final Hotels[] item = new Hotels[6];
ListView list;
TextView tv;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotels);
item[0] = new Hotels("emirxan",123,3);
item[1] = new Hotels("grand Samarkand",5,4);
item[2] = new Hotels("emirxan",123,3);
item[3] = new Hotels("grand Samarkand",5,4);
item[4] = new Hotels("emirxan",123,3);
item[5] = new Hotels("grand Samarkand",5,4);
//Json Parser
JSONArray jhotel = null;
String hotel = loadJSONFromAsset();
String name = null;
try {
JSONObject obj = new JSONObject(hotel);
jhotel = obj.getJSONArray("Hotel");
// looping through All Contacts
for (int i = 0; i < hotel.length(); i++) {
JSONObject c = jhotel.getJSONObject(i);
name = c.getString("Name");
String loc = c.getString("Location");
String addr = c.getString("Address");
String type = c.getString("Type");
String price = c.getString("Price");
String wi_fi = c.getString("Wi-Fi");
String open = c.getString("Open");
String tel = c.getString("Tel");
String url = c.getString("URL");
String description = c.getString("Description");
String rating = c.getString("Rating");
String photo = c.getString("Photo");
}
} catch (JSONException e) {
e.printStackTrace();
}
///
list = (ListView)findViewById(R.id.hotelsListView);
tv=(TextView)findViewById(R.id.hotelsTitle);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Baskerville.ttf");
tv.setTypeface(tf);
MyListAdapter adapter = new MyListAdapter(this,R.layout.list_item, item);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(HotelsActivity.this, HotelActivity.class);
startActivity(intent);
}
});
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Hotel.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_hotels, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| app/src/main/java/uz/samtuit/sammap/samapp/HotelsActivity.java | package uz.samtuit.sammap.samapp;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class HotelsActivity extends Activity {
final Hotels[] item = new Hotels[6];
ListView list;
TextView tv;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotels);
item[0] = new Hotels("emirxan",123,3);
item[1] = new Hotels("grand Samarkand",5,4);
item[2] = new Hotels("emirxan",123,3);
item[3] = new Hotels("grand Samarkand",5,4);
item[4] = new Hotels("emirxan",123,3);
item[5] = new Hotels("grand Samarkand",5,4);
list = (ListView)findViewById(R.id.hotelsListView);
tv=(TextView)findViewById(R.id.hotelsTitle);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Baskerville.ttf");
tv.setTypeface(tf);
MyListAdapter adapter = new MyListAdapter(this,R.layout.list_item, item);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(HotelsActivity.this, HotelActivity.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_hotels, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| Update HotelsActivity.java | app/src/main/java/uz/samtuit/sammap/samapp/HotelsActivity.java | Update HotelsActivity.java |
|
Java | lgpl-2.1 | 666f8bdd2fb8a404aa75fff6b6f6ca79b57320b7 | 0 | joshkh/intermine,tomck/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,joshkh/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,joshkh/intermine,zebrafishmine/intermine,tomck/intermine,JoeCarlson/intermine,joshkh/intermine,elsiklab/intermine,elsiklab/intermine,joshkh/intermine,kimrutherford/intermine,justincc/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,drhee/toxoMine,JoeCarlson/intermine,zebrafishmine/intermine,zebrafishmine/intermine,kimrutherford/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,justincc/intermine,tomck/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,zebrafishmine/intermine,kimrutherford/intermine,elsiklab/intermine,JoeCarlson/intermine,zebrafishmine/intermine,elsiklab/intermine,zebrafishmine/intermine,justincc/intermine,drhee/toxoMine,justincc/intermine,joshkh/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,justincc/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,zebrafishmine/intermine,kimrutherford/intermine,JoeCarlson/intermine,elsiklab/intermine,kimrutherford/intermine,elsiklab/intermine,elsiklab/intermine,drhee/toxoMine,zebrafishmine/intermine,kimrutherford/intermine,justincc/intermine,drhee/toxoMine,justincc/intermine,tomck/intermine,JoeCarlson/intermine,tomck/intermine,justincc/intermine,kimrutherford/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,kimrutherford/intermine,kimrutherford/intermine,JoeCarlson/intermine,drhee/toxoMine | package org.modmine.web.logic;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.intermine.api.query.PathQueryExecutor;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.api.results.ResultElement;
import org.intermine.bio.web.model.CytoscapeNetworkEdgeData;
import org.intermine.bio.web.model.CytoscapeNetworkNodeData;
import org.intermine.metadata.Model;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.PathQuery;
import org.modmine.web.model.RegulatoryNetworkEdgeData;
/**
* This class has the logics to query the database for modMine regulatory network information.
*
* @author Fengyuan Hu
*
*/
public final class RegulatoryNetworkDBUtil
{
@SuppressWarnings("unused")
private static final Logger LOG = Logger.getLogger(RegulatoryNetworkDBUtil.class);
private static Set<CytoscapeNetworkNodeData> interactionNodeSetFly = null;
private static Set<CytoscapeNetworkEdgeData> interactionEdgeSetFly = null;
private static Set<CytoscapeNetworkNodeData> interactionNodeSetWorm = null;
private static Set<CytoscapeNetworkEdgeData> interactionEdgeSetWorm = null;
private RegulatoryNetworkDBUtil() { }
// TODO use InterMine Id as identifier, fly is not applied.
//========== for Fly miRNA/gene - transcription factor interaction ==========
/**
* Get the fly network property/node information.
*
* @param model the Model
* @param executor the PathQueryExecutor
* @return a set of CytoscapeNetworkNodeData obj
*/
public static synchronized Set<CytoscapeNetworkNodeData> getFlyRegulatoryNodes(
Model model, PathQueryExecutor executor) {
// Check NetworkProperty class in the model
if (!model.getClassNames().contains(model.getPackageName() + ".NetworkProperty")) {
return null;
} else if (interactionNodeSetFly == null) {
queryFlyRegulatoryNodes(model, executor);
}
return interactionNodeSetFly;
}
/**
* Get the fly network regulation/edge information.
*
* @param model the Model
* @param executor the PathQueryExecutor
* @return a set of CytoscapeNetworkEdgeData obj
*/
public static synchronized Set<CytoscapeNetworkEdgeData> getFlyRegulatoryEdges(
Model model, PathQueryExecutor executor) {
// Check Regulation class in the model
if (!model.getClassNames().contains(model.getPackageName() + ".Regulation")) {
return null;
} else if (interactionEdgeSetFly == null) {
queryFlyRegulatoryEdges(model, executor);
}
return interactionEdgeSetFly;
}
/**
* Query all nodes of fly regulatory network.
*
* @param model the Model
* @param executor to run the query
* @return interactionNodeSet
*/
private static void queryFlyRegulatoryNodes(Model model, PathQueryExecutor executor) {
interactionNodeSetFly = new LinkedHashSet<CytoscapeNetworkNodeData>();
PathQuery query = new PathQuery(model);
query.addViews(
"NetworkProperty.node.primaryIdentifier",
"NetworkProperty.node.symbol",
"NetworkProperty.node.id",
"NetworkProperty.value"
);
query.addConstraint(Constraints.eq(
"NetworkProperty.node.primaryIdentifier", "FBgn*"));
ExportResultsIterator result = executor.execute(query);
while (result.hasNext()) {
List<ResultElement> row = result.next();
String featurePId = (String) row.get(0).getField();
String featureSymbol = (String) row.get(1).getField();
Integer featureIMId = (Integer) row.get(2).getField();
String position = (String) row.get(3).getField();
CytoscapeNetworkNodeData aNode = new CytoscapeNetworkNodeData();
aNode.setInterMineId(featureIMId);
aNode.setSoureceId(featurePId);
if (featureSymbol == null || featureSymbol.length() < 1) {
aNode.setSourceLabel(featurePId);
} else {
aNode.setSourceLabel(featureSymbol);
}
aNode.setPosition(position);
interactionNodeSetFly.add(aNode);
}
}
/**
* Query all edges of fly regulatory network.
*
* @param model the Model
* @param executor to run the query
* @return interactionEdgeSet
*/
private static void queryFlyRegulatoryEdges(Model model, PathQueryExecutor executor) {
interactionEdgeSetFly = new LinkedHashSet<CytoscapeNetworkEdgeData>();
PathQuery query = new PathQuery(model);
query.addViews(
"Regulation.type", // interaction type, e.g. TF-TF
"Regulation.source.primaryIdentifier",
"Regulation.source.symbol",
"Regulation.target.primaryIdentifier",
"Regulation.target.symbol"
);
query.addConstraint(
Constraints.eq("Regulation.source.primaryIdentifier", "FBgn*"),
"A");
query.addConstraint(
Constraints.eq("Regulation.target.primaryIdentifier", "FBgn*"),
"B");
query.setConstraintLogic("A and B");
ExportResultsIterator result = executor.execute(query);
while (result.hasNext()) {
List<ResultElement> row = result.next();
String interactionType = (String) row.get(0).getField();
String sourceNodePId = (String) row.get(1).getField();
String sourceNodeSymbol = (String) row.get(2).getField();
String targetNodePId = (String) row.get(3).getField();
String targetNodeSymbol = (String) row.get(4).getField();
CytoscapeNetworkEdgeData aEdge = new CytoscapeNetworkEdgeData();
// Handle bidirectional edges
if (interactionEdgeSetFly.isEmpty()) {
aEdge.setSourceId(sourceNodePId);
if (sourceNodeSymbol == null || sourceNodeSymbol.length() < 1) {
aEdge.setSourceLabel(sourceNodePId);
} else {
aEdge.setSourceLabel(sourceNodeSymbol);
}
aEdge.setTargetId(targetNodePId);
if (targetNodeSymbol == null || targetNodeSymbol.length() < 1) {
aEdge.setTargetLabel(targetNodePId);
} else {
aEdge.setTargetLabel(targetNodeSymbol);
}
aEdge.setInteractionType(interactionType);
aEdge.setDirection("one");
interactionEdgeSetFly.add(aEdge);
} else {
aEdge.setSourceId(sourceNodePId);
if (sourceNodeSymbol == null || sourceNodeSymbol.length() < 1) {
aEdge.setSourceLabel(sourceNodePId);
} else {
aEdge.setSourceLabel(sourceNodeSymbol);
}
aEdge.setTargetId(targetNodePId);
if (targetNodeSymbol == null || targetNodeSymbol.length() < 1) {
aEdge.setTargetLabel(targetNodePId);
} else {
aEdge.setTargetLabel(targetNodeSymbol);
}
// miRNA-TF and TF-miRNA are the same interaction type
if ("TF-miRNA".equals(interactionType) || "miRNA-TF".equals(interactionType)) {
String uniType = "miRNA-TF";
aEdge.setInteractionType(uniType);
} else {
aEdge.setInteractionType(interactionType);
}
String interactingString = aEdge.generateInteractionString();
String interactingStringRev = aEdge.generateReverseInteractionString();
// Get a list of interactionString from interactionSet
LinkedHashSet<String> intcStrSet = new LinkedHashSet<String>();
for (CytoscapeNetworkEdgeData edgedata : interactionEdgeSetFly) {
intcStrSet.add(edgedata.generateInteractionString());
}
// A none dulipcated edge
if (!(intcStrSet.contains(interactingString) || intcStrSet
.contains(interactingStringRev))) {
aEdge.setDirection("one");
interactionEdgeSetFly.add(aEdge);
} else { // duplicated edge
// Pull out the CytoscapeNetworkEdgeData which contains the current
// interactionString
for (CytoscapeNetworkEdgeData edgedata : interactionEdgeSetFly) {
if (edgedata.generateInteractionString().equals(interactingString)
|| edgedata.generateInteractionString().equals(interactingStringRev)) {
edgedata.setDirection("both");
aEdge.setInteractionType(interactionType);
}
}
}
}
}
}
//========== for Worm miRNA/gene - transcription factor interaction ==========
/**
* Get the worm network property/node information.
*
* @param model the Model
* @param executor the PathQueryExecutor
* @return a set of CytoscapeNetworkNodeData obj
*/
public static synchronized Set<CytoscapeNetworkNodeData> getWormRegulatoryNodes(
Model model, PathQueryExecutor executor) {
// Check NetworkProperty class in the model
if (!model.getClassNames().contains(model.getPackageName() + ".NetworkProperty")) {
return null;
} else if (interactionNodeSetWorm == null) {
queryWormRegulatoryNodes(model, executor);
}
return interactionNodeSetWorm;
}
/**
* Get the worm network regulation/edge information.
*
* @param model the Model
* @param executor the PathQueryExecutor
* @return a set of CytoscapeNetworkEdgeData obj
*/
public static synchronized Set<CytoscapeNetworkEdgeData> getWormRegulatoryEdges(
Model model, PathQueryExecutor executor) {
// Check Regulation class in the model
if (!model.getClassNames().contains(model.getPackageName() + ".Regulation")) {
return null;
} else if (interactionEdgeSetWorm == null) {
queryWormRegulatoryEdges(model, executor);
}
return interactionEdgeSetWorm;
}
/**
* Query all nodes of worm regulatory network.
*
* @param model the Model
* @param executor to run the query
* @return interactionNodeSet
*/
private static void queryWormRegulatoryNodes(Model model, PathQueryExecutor executor) {
interactionNodeSetWorm = new LinkedHashSet<CytoscapeNetworkNodeData>();
PathQuery query = new PathQuery(model);
query.addViews(
"NetworkProperty.node.primaryIdentifier",
"NetworkProperty.node.symbol",
"NetworkProperty.node.id",
"NetworkProperty.type",
"NetworkProperty.value"
);
query.addConstraint(Constraints.eq(
"NetworkProperty.node.organism.shortName", "C. elegans"));
ExportResultsIterator result = executor.execute(query);
while (result.hasNext()) {
List<ResultElement> row = result.next();
String featurePId = (String) row.get(0).getField();
String featureSymbol = (String) row.get(1).getField();
Integer id = (Integer) row.get(2).getField();
String key = (String) row.get(3).getField();
String value = (String) row.get(4).getField();
CytoscapeNetworkNodeData aNode = new CytoscapeNetworkNodeData();
aNode.setInterMineId(id);
aNode.setSoureceId(String.valueOf(id)); // Use IM Id instead of PId
if (featureSymbol == null || featureSymbol.length() < 1) {
aNode.setSourceLabel(featurePId);
} else {
aNode.setSourceLabel(featureSymbol);
}
if (interactionNodeSetWorm.contains(aNode)) {
for (CytoscapeNetworkNodeData n : interactionNodeSetWorm) {
if (n.getInterMineId() == id) {
n.getExtraInfo().put(key, value);
}
}
} else {
Map<String, String> extraInfo = new HashMap<String, String>();
extraInfo.put(key, value);
aNode.setExtraInfo(extraInfo);
}
interactionNodeSetWorm.add(aNode);
}
}
/**
* Query all edges of worm regulatory network.
*
* @param model the Model
* @param executor to run the query
* @return interactionEdgeSet
*/
private static void queryWormRegulatoryEdges(Model model, PathQueryExecutor executor) {
interactionEdgeSetWorm = new LinkedHashSet<CytoscapeNetworkEdgeData>();
PathQuery query = new PathQuery(model);
query.addViews(
"Regulation.type", // interaction type, e.g. TF-TF
"Regulation.source.primaryIdentifier",
"Regulation.source.symbol",
"Regulation.source.id",
"Regulation.target.primaryIdentifier",
"Regulation.target.symbol",
"Regulation.target.id"
);
query.addConstraint(Constraints.eq("Regulation.source.organism.shortName", "C. elegans"));
ExportResultsIterator result = executor.execute(query);
while (result.hasNext()) {
List<ResultElement> row = result.next();
String interactionType = (String) row.get(0).getField();
String sourcePId = (String) row.get(1).getField();
String sourceSymbol = (String) row.get(2).getField();
Integer sourceId = (Integer) row.get(3).getField();
String targetPId = (String) row.get(4).getField();
String targetSymbol = (String) row.get(5).getField();
Integer targetId = (Integer) row.get(6).getField();
// TODO Hack for a database issue
if ("blmp-1".equals(targetSymbol)) {
targetId = 1348007904;
}
if ("unc-130".equals(targetSymbol)) {
targetId = 1348015202;
}
if ("mab-5".equals(targetSymbol)) {
targetId = 1348006300;
}
if ("mdl-1".equals(targetSymbol)) {
targetId = 1348006399;
}
if ("elt-3".equals(targetSymbol)) {
targetId = 1348003204;
}
if ("lin-11".equals(targetSymbol)) {
targetId = 1348006039;
}
if ("skn-1".equals(targetSymbol)) {
targetId = 1348009973;
}
if ("egl-27".equals(targetSymbol)) {
targetId = 1348003074;
}
CytoscapeNetworkEdgeData aEdge = new RegulatoryNetworkEdgeData();
aEdge.setSourceId(String.valueOf(sourceId));
if (sourceSymbol == null || sourceSymbol.length() < 1) {
aEdge.setSourceLabel(sourcePId);
} else {
aEdge.setSourceLabel(sourceSymbol);
}
aEdge.setTargetId(String.valueOf(targetId));
if (targetSymbol == null || targetSymbol.length() < 1) {
aEdge.setTargetLabel(targetPId);
} else {
aEdge.setTargetLabel(targetSymbol);
}
aEdge.setInteractionType(interactionType);
interactionEdgeSetWorm.add(aEdge);
}
}
}
| modmine/webapp/src/org/modmine/web/logic/RegulatoryNetworkDBUtil.java | package org.modmine.web.logic;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.intermine.api.query.PathQueryExecutor;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.api.results.ResultElement;
import org.intermine.bio.web.model.CytoscapeNetworkEdgeData;
import org.intermine.bio.web.model.CytoscapeNetworkNodeData;
import org.intermine.metadata.Model;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.PathQuery;
import org.modmine.web.model.RegulatoryNetworkEdgeData;
/**
* This class has the logics to query the database for modMine regulatory network information.
*
* @author Fengyuan Hu
*
*/
public final class RegulatoryNetworkDBUtil
{
@SuppressWarnings("unused")
private static final Logger LOG = Logger.getLogger(RegulatoryNetworkDBUtil.class);
private static Set<CytoscapeNetworkNodeData> interactionNodeSetFly = null;
private static Set<CytoscapeNetworkEdgeData> interactionEdgeSetFly = null;
private static Set<CytoscapeNetworkNodeData> interactionNodeSetWorm = null;
private static Set<CytoscapeNetworkEdgeData> interactionEdgeSetWorm = null;
private RegulatoryNetworkDBUtil() { }
// TODO use InterMine Id as identifier, fly is not applied.
//========== for Fly miRNA/gene - transcription factor interaction ==========
/**
* Get the fly network property/node information.
*
* @param model the Model
* @param executor the PathQueryExecutor
* @return a set of CytoscapeNetworkNodeData obj
*/
public static synchronized Set<CytoscapeNetworkNodeData> getFlyRegulatoryNodes(
Model model, PathQueryExecutor executor) {
// Check NetworkProperty class in the model
if (!model.getClassNames().contains(model.getPackageName() + ".NetworkProperty")) {
return null;
} else if (interactionNodeSetFly == null) {
queryFlyRegulatoryNodes(model, executor);
}
return interactionNodeSetFly;
}
/**
* Get the fly network regulation/edge information.
*
* @param model the Model
* @param executor the PathQueryExecutor
* @return a set of CytoscapeNetworkEdgeData obj
*/
public static synchronized Set<CytoscapeNetworkEdgeData> getFlyRegulatoryEdges(
Model model, PathQueryExecutor executor) {
// Check Regulation class in the model
if (!model.getClassNames().contains(model.getPackageName() + ".Regulation")) {
return null;
} else if (interactionEdgeSetFly == null) {
queryFlyRegulatoryEdges(model, executor);
}
return interactionEdgeSetFly;
}
/**
* Query all nodes of fly regulatory network.
*
* @param model the Model
* @param executor to run the query
* @return interactionNodeSet
*/
private static void queryFlyRegulatoryNodes(Model model, PathQueryExecutor executor) {
interactionNodeSetFly = new LinkedHashSet<CytoscapeNetworkNodeData>();
PathQuery query = new PathQuery(model);
query.addViews(
"NetworkProperty.node.primaryIdentifier",
"NetworkProperty.node.symbol",
"NetworkProperty.node.id",
"NetworkProperty.value"
);
query.addConstraint(Constraints.eq(
"NetworkProperty.node.primaryIdentifier", "FBgn*"));
ExportResultsIterator result = executor.execute(query);
while (result.hasNext()) {
List<ResultElement> row = result.next();
String featurePId = (String) row.get(0).getField();
String featureSymbol = (String) row.get(1).getField();
Integer featureIMId = (Integer) row.get(2).getField();
String position = (String) row.get(3).getField();
CytoscapeNetworkNodeData aNode = new CytoscapeNetworkNodeData();
aNode.setInterMineId(featureIMId);
aNode.setSoureceId(featurePId);
if (featureSymbol == null || featureSymbol.length() < 1) {
aNode.setSourceLabel(featurePId);
} else {
aNode.setSourceLabel(featureSymbol);
}
aNode.setPosition(position);
interactionNodeSetFly.add(aNode);
}
}
/**
* Query all edges of fly regulatory network.
*
* @param model the Model
* @param executor to run the query
* @return interactionEdgeSet
*/
private static void queryFlyRegulatoryEdges(Model model, PathQueryExecutor executor) {
interactionEdgeSetFly = new LinkedHashSet<CytoscapeNetworkEdgeData>();
PathQuery query = new PathQuery(model);
query.addViews(
"Regulation.type", // interaction type, e.g. TF-TF
"Regulation.source.primaryIdentifier",
"Regulation.source.symbol",
"Regulation.target.primaryIdentifier",
"Regulation.target.symbol"
);
query.addConstraint(
Constraints.eq("Regulation.source.primaryIdentifier", "FBgn*"),
"A");
query.addConstraint(
Constraints.eq("Regulation.target.primaryIdentifier", "FBgn*"),
"B");
query.setConstraintLogic("A and B");
ExportResultsIterator result = executor.execute(query);
while (result.hasNext()) {
List<ResultElement> row = result.next();
String interactionType = (String) row.get(0).getField();
String sourceNodePId = (String) row.get(1).getField();
String sourceNodeSymbol = (String) row.get(2).getField();
String targetNodePId = (String) row.get(3).getField();
String targetNodeSymbol = (String) row.get(4).getField();
CytoscapeNetworkEdgeData aEdge = new CytoscapeNetworkEdgeData();
// Handle bidirectional edges
if (interactionEdgeSetFly.isEmpty()) {
aEdge.setSourceId(sourceNodePId);
if (sourceNodeSymbol == null || sourceNodeSymbol.length() < 1) {
aEdge.setSourceLabel(sourceNodePId);
} else {
aEdge.setSourceLabel(sourceNodeSymbol);
}
aEdge.setTargetId(targetNodePId);
if (targetNodeSymbol == null || targetNodeSymbol.length() < 1) {
aEdge.setTargetLabel(targetNodePId);
} else {
aEdge.setTargetLabel(targetNodeSymbol);
}
aEdge.setInteractionType(interactionType);
aEdge.setDirection("one");
interactionEdgeSetFly.add(aEdge);
} else {
aEdge.setSourceId(sourceNodePId);
if (sourceNodeSymbol == null || sourceNodeSymbol.length() < 1) {
aEdge.setSourceLabel(sourceNodePId);
} else {
aEdge.setSourceLabel(sourceNodeSymbol);
}
aEdge.setTargetId(targetNodePId);
if (targetNodeSymbol == null || targetNodeSymbol.length() < 1) {
aEdge.setTargetLabel(targetNodePId);
} else {
aEdge.setTargetLabel(targetNodeSymbol);
}
// miRNA-TF and TF-miRNA are the same interaction type
if ("TF-miRNA".equals(interactionType) || "miRNA-TF".equals(interactionType)) {
String uniType = "miRNA-TF";
aEdge.setInteractionType(uniType);
} else {
aEdge.setInteractionType(interactionType);
}
String interactingString = aEdge.generateInteractionString();
String interactingStringRev = aEdge.generateReverseInteractionString();
// Get a list of interactionString from interactionSet
LinkedHashSet<String> intcStrSet = new LinkedHashSet<String>();
for (CytoscapeNetworkEdgeData edgedata : interactionEdgeSetFly) {
intcStrSet.add(edgedata.generateInteractionString());
}
// A none dulipcated edge
if (!(intcStrSet.contains(interactingString) || intcStrSet
.contains(interactingStringRev))) {
aEdge.setDirection("one");
interactionEdgeSetFly.add(aEdge);
} else { // duplicated edge
// Pull out the CytoscapeNetworkEdgeData which contains the current
// interactionString
for (CytoscapeNetworkEdgeData edgedata : interactionEdgeSetFly) {
if (edgedata.generateInteractionString().equals(interactingString)
|| edgedata.generateInteractionString().equals(interactingStringRev)) {
edgedata.setDirection("both");
aEdge.setInteractionType(interactionType);
}
}
}
}
}
}
//========== for Worm miRNA/gene - transcription factor interaction ==========
/**
* Get the worm network property/node information.
*
* @param model the Model
* @param executor the PathQueryExecutor
* @return a set of CytoscapeNetworkNodeData obj
*/
public static synchronized Set<CytoscapeNetworkNodeData> getWormRegulatoryNodes(
Model model, PathQueryExecutor executor) {
// Check NetworkProperty class in the model
if (!model.getClassNames().contains(model.getPackageName() + ".NetworkProperty")) {
return null;
} else if (interactionNodeSetWorm == null) {
queryWormRegulatoryNodes(model, executor);
}
return interactionNodeSetWorm;
}
/**
* Get the worm network regulation/edge information.
*
* @param model the Model
* @param executor the PathQueryExecutor
* @return a set of CytoscapeNetworkEdgeData obj
*/
public static synchronized Set<CytoscapeNetworkEdgeData> getWormRegulatoryEdges(
Model model, PathQueryExecutor executor) {
// Check Regulation class in the model
if (!model.getClassNames().contains(model.getPackageName() + ".Regulation")) {
return null;
} else if (interactionEdgeSetWorm == null) {
queryWormRegulatoryEdges(model, executor);
}
return interactionEdgeSetWorm;
}
/**
* Query all nodes of worm regulatory network.
*
* @param model the Model
* @param executor to run the query
* @return interactionNodeSet
*/
private static void queryWormRegulatoryNodes(Model model, PathQueryExecutor executor) {
interactionNodeSetWorm = new LinkedHashSet<CytoscapeNetworkNodeData>();
PathQuery query = new PathQuery(model);
query.addViews(
"NetworkProperty.node.primaryIdentifier",
"NetworkProperty.node.symbol",
"NetworkProperty.node.id",
"NetworkProperty.type",
"NetworkProperty.value"
);
query.addConstraint(Constraints.eq(
"NetworkProperty.node.organism.shortName", "C. elegans"));
ExportResultsIterator result = executor.execute(query);
while (result.hasNext()) {
List<ResultElement> row = result.next();
String featurePId = (String) row.get(0).getField();
String featureSymbol = (String) row.get(1).getField();
Integer id = (Integer) row.get(2).getField();
String key = (String) row.get(3).getField();
String value = (String) row.get(4).getField();
CytoscapeNetworkNodeData aNode = new CytoscapeNetworkNodeData();
aNode.setInterMineId(id);
aNode.setSoureceId(String.valueOf(id)); // Use IM Id instead of PId
if (featureSymbol == null || featureSymbol.length() < 1) {
aNode.setSourceLabel(featurePId);
} else {
aNode.setSourceLabel(featureSymbol);
}
if (interactionNodeSetWorm.contains(aNode)) {
for (CytoscapeNetworkNodeData n : interactionNodeSetWorm) {
if (n.getInterMineId() == id) {
n.getExtraInfo().put(key, value);
}
}
} else {
Map<String, String> extraInfo = new HashMap<String, String>();
extraInfo.put(key, value);
aNode.setExtraInfo(extraInfo);
}
interactionNodeSetWorm.add(aNode);
}
}
/**
* Query all edges of worm regulatory network.
*
* @param model the Model
* @param executor to run the query
* @return interactionEdgeSet
*/
private static void queryWormRegulatoryEdges(Model model, PathQueryExecutor executor) {
interactionEdgeSetWorm = new LinkedHashSet<CytoscapeNetworkEdgeData>();
PathQuery query = new PathQuery(model);
query.addViews(
"Regulation.type", // interaction type, e.g. TF-TF
"Regulation.source.primaryIdentifier",
"Regulation.source.symbol",
"Regulation.source.id",
"Regulation.target.primaryIdentifier",
"Regulation.target.symbol",
"Regulation.target.id"
);
query.addConstraint(Constraints.eq("Regulation.source.organism.shortName", "C. elegans"));
ExportResultsIterator result = executor.execute(query);
while (result.hasNext()) {
List<ResultElement> row = result.next();
String interactionType = (String) row.get(0).getField();
String sourcePId = (String) row.get(1).getField();
String sourceSymbol = (String) row.get(2).getField();
Integer sourceId = (Integer) row.get(3).getField();
String targetPId = (String) row.get(4).getField();
String targetSymbol = (String) row.get(5).getField();
Integer targetId = (Integer) row.get(6).getField();
// TODO Hack for a database issue
if ("blmp-1".equals(targetSymbol)) {
targetId = 1122002752;
}
if ("unc-130".equals(targetSymbol)) {
targetId = 1122124362;
}
if ("mab-5".equals(targetSymbol)) {
targetId = 1122248670;
}
if ("mdl-1".equals(targetSymbol)) {
targetId = 1122662331;
}
if ("elt-3".equals(targetSymbol)) {
targetId = 1122661930;
}
if ("lin-11".equals(targetSymbol)) {
targetId = 1122002014;
}
if ("skn-1".equals(targetSymbol)) {
targetId = 1122360407;
}
if ("egl-27".equals(targetSymbol)) {
targetId = 1122131388;
}
CytoscapeNetworkEdgeData aEdge = new RegulatoryNetworkEdgeData();
aEdge.setSourceId(String.valueOf(sourceId));
if (sourceSymbol == null || sourceSymbol.length() < 1) {
aEdge.setSourceLabel(sourcePId);
} else {
aEdge.setSourceLabel(sourceSymbol);
}
aEdge.setTargetId(String.valueOf(targetId));
if (targetSymbol == null || targetSymbol.length() < 1) {
aEdge.setTargetLabel(targetPId);
} else {
aEdge.setTargetLabel(targetSymbol);
}
aEdge.setInteractionType(interactionType);
interactionEdgeSetWorm.add(aEdge);
}
}
}
| modMine release fixes
| modmine/webapp/src/org/modmine/web/logic/RegulatoryNetworkDBUtil.java | modMine release fixes |
|
Java | apache-2.0 | 1139616ebbcf85ce667a2e856c5cd18b0b68b5f9 | 0 | opensourcegamedev/SpaceChaos | package dev.game.spacechaos.game.entities;
/**
* Created by Justin on 29.03.2017.
*/
public abstract class Entity {
//current absolute position of entity
private volatile float xPos = 0;
private volatile float yPos = 0;
//current dimension of entity
private volatile float width = 0;
protected volatile float height = 0;
/**
* default constructor
*
* @param xPos x position
* @param yPos y position
*/
public Entity (float xPos, float yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
/**
* get absolute x position of entity
*
* @return x position
*/
public float getX () {
return this.xPos;
}
/**
* get absolute y position of entity
*
* @return y position
*/
public float getY () {
return this.yPos;
}
/**
* set absolute position of entity
*
* @param x x position
* @param y y position
*/
public void setPos (float x, float y) {
this.xPos = x;
this.yPos = y;
}
/**
* move entity
*
* @param x speed x
* @param y speed y
*/
public void move (float x, float y) {
this.xPos += x;
this.yPos += y;
}
/**
* get current width of entity
*
* @return width of entity
*/
public float getWidth () {
return this.width;
}
/**
* get current height of entity
*
* @return height of entity
*/
public float getHeight () {
return this.height;
}
/**
* set dimension of entity
*
* @param width width of entity
* @param height height of entity
*/
public void setDimension (float width, float height) {
this.width = width;
this.height = height;
}
/**
* get center x position of entity
*
* @return center x position
*/
public float getMiddleX () {
return this.getX() + (width / 2);
}
/**
* get center y position of entity
*
* @return center y position
*/
public float getMiddleY () {
return this.getY() + (height / 2);
}
/**
* cleanUp entity and dispose all resources / assets
*/
public abstract void destroy ();
}
| game/src/main/java/dev/game/spacechaos/game/entities/Entity.java | package dev.game.spacechaos.game.entities;
/**
* Created by Justin on 29.03.2017.
*/
public abstract class Entity {
//current absolute position of entity
private volatile float xPos = 0;
private volatile float yPos = 0;
//current dimension of entity
private volatile float width = 0;
protected volatile float height = 0;
/**
* default constructor
*
* @param xPos x position
* @param yPos y position
*/
public Entity (float xPos, float yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
/**
* get absolute x position of entity
*
* @return x position
*/
public float getX () {
return this.xPos;
}
/**
* get absolute y position of entity
*
* @return y position
*/
public float getY () {
return this.yPos;
}
public void setPos (float x, float y) {
this.xPos = x;
this.yPos = y;
}
public void move (float x, float y) {
this.xPos += x;
this.yPos += y;
}
public float getWidth () {
return this.width;
}
public float getHeight () {
return this.height;
}
public void setDimension (float width, float height) {
this.width = width;
this.height = height;
}
public float getMiddleX () {
return this.getX() + (width / 2);
}
public float getMiddleY () {
return this.getY() + (height / 2);
}
public abstract void destroy ();
}
| added javadocs.
| game/src/main/java/dev/game/spacechaos/game/entities/Entity.java | added javadocs. |
|
Java | apache-2.0 | 57ac081708e2cee579601334019687899e153261 | 0 | shapesecurity/shift-java,shapesecurity/shift-java,shapesecurity/shift-java | /*
* Copyright 2014 Shape Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.shapesecurity.shift.validator;
import com.shapesecurity.functional.data.ImmutableList;
import com.shapesecurity.functional.data.Maybe;
import com.shapesecurity.shift.ast.*;
import com.shapesecurity.shift.parser.JsError;
import com.shapesecurity.shift.parser.Parser;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UnitTest {
private void assertCorrectFailures(Script script, int expectedNumErrors, String expectedErrorMsg) {
ImmutableList<ValidationError> errors = Validator.validate(script);
assertEquals(expectedNumErrors, errors.length);
for (ValidationError error : errors) {
assertEquals(error.message, expectedErrorMsg);
}
}
private void assertCorrectFailures(Module module, int expectedNumErrors, String expectedErrorMsg) {
ImmutableList<ValidationError> errors = Validator.validate(module);
assertEquals(expectedNumErrors, errors.length);
for (ValidationError error : errors) {
assertEquals(error.message, expectedErrorMsg);
}
}
@Test
public void testBindingIdentifier() throws JsError {
Script test0 = Parser.parseScript("x=1");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new AssignmentExpression(new BindingIdentifier("1"), new LiteralNumericExpression(0.0)))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_BINDING_IDENTIFIER_NAME);
}
@Test
public void testBreakStatement() throws JsError {
Script test0 = Parser.parseScript("for(var i = 0; i < 10; i++) { break; }");
assertCorrectFailures(test0, 0, "");
Script test1 = Parser.parseScript("done: while (true) { break done; }");
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("done", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new BreakStatement(Maybe.just("1done")))))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_BREAK_STATEMENT_LABEL);
}
@Test
public void testCatchClause() throws JsError {
Script test0 = Parser.parseScript("try{} catch(e){} finally{}");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new TryFinallyStatement(new Block(ImmutableList.nil()), Maybe.just(new CatchClause(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), new Block(ImmutableList.nil()))), new Block(ImmutableList.nil()))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.CATCH_CLAUSE_BINDING_NOT_MEMBER_EXPRESSION);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new TryFinallyStatement(new Block(ImmutableList.nil()), Maybe.just(new CatchClause(new StaticMemberExpression("a", new IdentifierExpression("b")), new Block(ImmutableList.nil()))), new Block(ImmutableList.nil()))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.CATCH_CLAUSE_BINDING_NOT_MEMBER_EXPRESSION);
}
@Test
public void testContinueStatement() throws JsError {
Script test0 = Parser.parseScript("for(var i = 0; i < 10; i++) { continue; }");
assertCorrectFailures(test0, 0, "");
Script test1 = Parser.parseScript("done: while (true) { continue done; }");
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("done", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new ContinueStatement(Maybe.just("1done")))))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_CONTINUE_STATEMENT_LABEL);
}
@Test
public void testDirective() {
Script test0 = new Script(ImmutableList.list(new Directive("use strict;"), new Directive("linda;"), new Directive(".-#($*&#")), ImmutableList.nil());
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.list(new Directive("'use strict;")), ImmutableList.nil());
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_DIRECTIVE);
Script test2 = new Script(ImmutableList.list(new Directive("'use strict;"), new Directive("linda';"), new Directive("'.-#($*&#")), ImmutableList.nil());
assertCorrectFailures(test2, 3, ValidationErrorMessages.VALID_DIRECTIVE);
Script test3 = new Script(ImmutableList.list(new Directive("'use stri\"ct;"), new Directive("li\"nda;'"), new Directive(".-\"#'($*&#")), ImmutableList.nil());
assertCorrectFailures(test3, 3, ValidationErrorMessages.VALID_DIRECTIVE);
Script test4 = new Script(ImmutableList.list(new Directive("'use s\ntrict;"), new Directive("lind\na;'"), new Directive(".-#'($\n*&#")), ImmutableList.nil());
assertCorrectFailures(test4, 3, ValidationErrorMessages.VALID_DIRECTIVE);
Script test5 = new Script(ImmutableList.list(new Directive("'use s\rtrict;"), new Directive("lind\ra;'"), new Directive(".-#'($\r*&#")), ImmutableList.nil());
assertCorrectFailures(test5, 3, ValidationErrorMessages.VALID_DIRECTIVE);
Script test6 = new Script(ImmutableList.list(new Directive("('\\x0');"), new Directive("('\u2028')"), new Directive("(\\u{110000}\\\")")), ImmutableList.nil());
assertCorrectFailures(test6, 3, ValidationErrorMessages.VALID_DIRECTIVE);
}
@Test
public void testExportSpecifier() throws JsError {
Module test0 = Parser.parseModule("export * from 'a';");
assertCorrectFailures(test0, 0, "");
Module test1 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportFrom(ImmutableList.list(new ExportSpecifier(Maybe.just("2a_"), "b")), Maybe.just("a"))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_EXPORT_SPECIFIER_NAME);
Module test2 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportFrom(ImmutableList.list(new ExportSpecifier(Maybe.just("b"), "%dlk45")), Maybe.just("a"))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_EXPORTED_NAME);
Module test3 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportFrom(ImmutableList.list(new ExportSpecifier(Maybe.nothing(), "a")), Maybe.just("a"))));
assertCorrectFailures(test3, 0, "");
}
@Test
public void testForInStatement() throws JsError {
Script test0 = Parser.parseScript("for (var x in [1,2,3]){}");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test1, 1, ValidationErrorMessages.ONE_VARIABLE_DECLARATOR_IN_FOR_IN);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test2, 1, ValidationErrorMessages.ONE_VARIABLE_DECLARATOR_IN_FOR_IN);
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test3, 1, ValidationErrorMessages.ONE_VARIABLE_DECLARATOR_IN_FOR_IN);
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test4, 1, ValidationErrorMessages.NO_INIT_IN_VARIABLE_DECLARATOR_IN_FOR_IN);
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test5, 1, ValidationErrorMessages.NO_INIT_IN_VARIABLE_DECLARATOR_IN_FOR_IN);
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test6, 1, ValidationErrorMessages.NO_INIT_IN_VARIABLE_DECLARATOR_IN_FOR_IN);
}
@Test
public void testForOfStatement() throws JsError {
Script test0 = Parser.parseScript("for (var x of [1,2,3]){}");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test1, 1, ValidationErrorMessages.ONE_VARIABLE_DECLARATOR_IN_FOR_OF);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test2, 1, ValidationErrorMessages.ONE_VARIABLE_DECLARATOR_IN_FOR_OF);
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test3, 1, ValidationErrorMessages.ONE_VARIABLE_DECLARATOR_IN_FOR_OF);
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test4, 1, ValidationErrorMessages.NO_INIT_IN_VARIABLE_DECLARATOR_IN_FOR_OF);
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test5, 1, ValidationErrorMessages.NO_INIT_IN_VARIABLE_DECLARATOR_IN_FOR_OF);
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test6, 1, ValidationErrorMessages.NO_INIT_IN_VARIABLE_DECLARATOR_IN_FOR_OF);
}
@Test
public void testFormalParameters() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new BindingIdentifier("a")), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.FORMAL_PARAMETER_ITEMS_NOT_MEMBER_EXPRESSION);
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new StaticMemberExpression("a", new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test3, 1, ValidationErrorMessages.FORMAL_PARAMETER_ITEMS_NOT_MEMBER_EXPRESSION);
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new BindingWithDefault(new BindingIdentifier("a"), new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test4, 0, "");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new BindingWithDefault(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test5, 1, ValidationErrorMessages.FORMAL_PARAMETER_ITEMS_BINDING_NOT_MEMBER_EXPRESSION);
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new BindingWithDefault(new StaticMemberExpression("a", new IdentifierExpression("b")), new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test6, 1, ValidationErrorMessages.FORMAL_PARAMETER_ITEMS_BINDING_NOT_MEMBER_EXPRESSION);
}
@Test
public void testIdentifierExpression() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("linda"))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("9458723"))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_IDENTIFIER_NAME);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("A*9458723"))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_IDENTIFIER_NAME);
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("0lkdjaf"))));
assertCorrectFailures(test3, 1, ValidationErrorMessages.VALID_IDENTIFIER_NAME);
}
@Test
public void testIfStatement() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new IfStatement(new ThisExpression(), new ExpressionStatement(new ThisExpression()), Maybe.just(new ExpressionStatement(new ThisExpression())))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new IfStatement(new IdentifierExpression("a"), new ExpressionStatement(new IdentifierExpression("b")), Maybe.nothing())));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new IfStatement(new IdentifierExpression("a"), new IfStatement(new ThisExpression(), new ExpressionStatement(new ThisExpression()), Maybe.nothing()), Maybe.just(new ExpressionStatement(new ThisExpression())))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_IF_STATEMENT);
}
@Test
public void testImportSpecifier() {
Module test0 = new Module(ImmutableList.nil(), ImmutableList.list(new Import(Maybe.just(new BindingIdentifier("a")), ImmutableList.list(new ImportSpecifier(Maybe.nothing(), new BindingIdentifier("b"))), "c")));
assertCorrectFailures(test0, 0, "");
Module test1 = new Module(ImmutableList.nil(), ImmutableList.list(new Import(Maybe.just(new BindingIdentifier("a")), ImmutableList.list(new ImportSpecifier(Maybe.just("a"), new BindingIdentifier("b"))), "c")));
assertCorrectFailures(test1, 0, "");
Module test2 = new Module(ImmutableList.nil(), ImmutableList.list(new Import(Maybe.just(new BindingIdentifier("a")), ImmutableList.list(new ImportSpecifier(Maybe.just("2d849"), new BindingIdentifier("b"))), "c")));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_IMPORT_SPECIFIER_NAME);
}
@Test
public void testLabeledStatement() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("done", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new BreakStatement(Maybe.just("done")))))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("5346done", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new BreakStatement(Maybe.just("done")))))))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_LABEL);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("#das*($839da", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new ContinueStatement(Maybe.just("done")))))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_LABEL);
}
@Test
public void testLiteralNumericExpression() throws JsError {
Script test0 = Parser.parseScript("1.0");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralNumericExpression(-1.0))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.LITERAL_NUMERIC_VALUE_NOT_NEGATIVE);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralNumericExpression(1.0/0))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.LITERAL_NUMERIC_VALUE_NOT_INFINITE);
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralNumericExpression(Double.NaN))));
assertCorrectFailures(test3, 1, ValidationErrorMessages.LITERAL_NUMERIC_VALUE_NOT_NAN);
}
@Test
public void testLiteralRegExpExpression() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralRegExpExpression("@", ""))));
assertCorrectFailures(test0, 1, ValidationErrorMessages.VALID_REG_EX_PATTERN);
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralRegExpExpression("/a/", "j"))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_REG_EX_FLAG);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralRegExpExpression("/a/", "gg"))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.NO_DUPLICATE_REG_EX_FLAG);
}
@Test
public void testSetter() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new BindingIdentifier("w"), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.SETTER_PARAM_NOT_MEMBER_EXPRESSION);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new StaticMemberExpression("a", new IdentifierExpression("b")), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.SETTER_PARAM_NOT_MEMBER_EXPRESSION);
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new BindingWithDefault(new BindingIdentifier("a"), new LiteralNumericExpression(0.0)), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test3, 0, "");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new BindingWithDefault(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), new LiteralNumericExpression(0.0)), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test4, 1, ValidationErrorMessages.SETTER_PARAM_BINDING_NOT_MEMBER_EXPRESSION);
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new BindingWithDefault(new StaticMemberExpression("a", new IdentifierExpression("b")), new LiteralNumericExpression(0.0)), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test5, 1, ValidationErrorMessages.SETTER_PARAM_BINDING_NOT_MEMBER_EXPRESSION);
}
@Test
public void testShorthandProperty() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new ShorthandProperty("a"), new ShorthandProperty("asajd_nk"))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new ShorthandProperty("429adk"), new ShorthandProperty("asajd_nk"))))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_SHORTHAND_PROPERTY_NAME);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new ShorthandProperty("a"), new ShorthandProperty("^34d9"))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_SHORTHAND_PROPERTY_NAME);
}
@Test
public void testStaticMemberExpression() throws JsError {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new StaticMemberExpression("b", new IdentifierExpression("a")))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new StaticMemberExpression("45829", new IdentifierExpression("a")))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_STATIC_MEMBER_EXPRESSION_PROPERTY_NAME);
}
@Test
public void testTemplateElement() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("abc"))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("\"abc'"))))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_TEMPLATE_ELEMENT_VALUE);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("'abc\""))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_TEMPLATE_ELEMENT_VALUE);
}
@Test
public void testTemplateExpression() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("a"), new IdentifierExpression("b"), new TemplateElement("c"))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new IdentifierExpression("b"), new TemplateElement("c"))))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.ALTERNATING_TEMPLATE_EXPRESSION_ELEMENTS);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("a"), new IdentifierExpression("b"), new TemplateElement("c"), new TemplateElement("c"), new TemplateElement("c"))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.ALTERNATING_TEMPLATE_EXPRESSION_ELEMENTS);
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new IdentifierExpression("b"), new TemplateElement("c"), new IdentifierExpression("b"))))));
assertCorrectFailures(test3, 3, ValidationErrorMessages.ALTERNATING_TEMPLATE_EXPRESSION_ELEMENTS);
}
@Test
public void testVariableDeclaration() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test2, 0, "");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list()))));
assertCorrectFailures(test3, 1, ValidationErrorMessages.NOT_EMPTY_VARIABLE_DECLARATORS_LIST);
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list()))));
assertCorrectFailures(test4, 1, ValidationErrorMessages.NOT_EMPTY_VARIABLE_DECLARATORS_LIST);
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list()))));
assertCorrectFailures(test5, 1, ValidationErrorMessages.NOT_EMPTY_VARIABLE_DECLARATORS_LIST);
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.nil()))));
assertCorrectFailures(test6, 1, ValidationErrorMessages.NOT_EMPTY_VARIABLE_DECLARATORS_LIST);
Script test7 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.nil()))));
assertCorrectFailures(test7, 1, ValidationErrorMessages.NOT_EMPTY_VARIABLE_DECLARATORS_LIST);
Script test8 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.nil()))));
assertCorrectFailures(test8, 1, ValidationErrorMessages.NOT_EMPTY_VARIABLE_DECLARATORS_LIST);
}
@Test
public void testVariableDeclarationStatement() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test2, 0, "");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()))))));
assertCorrectFailures(test3, 0, "");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()))))));
assertCorrectFailures(test4, 0, "");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()))))));
assertCorrectFailures(test5, 1, ValidationErrorMessages.CONST_VARIABLE_DECLARATION_MUST_HAVE_INIT);
}
@Test
public void testVariableDeclarator() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test2, 0, "");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test3, 1, ValidationErrorMessages.VARIABLE_DECLARATION_BINDING_NOT_MEMBER_EXPRESSION);
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new StaticMemberExpression("a", new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test4, 1, ValidationErrorMessages.VARIABLE_DECLARATION_BINDING_NOT_MEMBER_EXPRESSION);
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test5, 1, ValidationErrorMessages.VARIABLE_DECLARATION_BINDING_NOT_MEMBER_EXPRESSION);
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new StaticMemberExpression("a", new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test6, 1, ValidationErrorMessages.VARIABLE_DECLARATION_BINDING_NOT_MEMBER_EXPRESSION);
Script test7 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test7, 1, ValidationErrorMessages.VARIABLE_DECLARATION_BINDING_NOT_MEMBER_EXPRESSION);
Script test8 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new StaticMemberExpression("a", new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test8, 1, ValidationErrorMessages.VARIABLE_DECLARATION_BINDING_NOT_MEMBER_EXPRESSION);
}
@Test
public void testBindingIdentifierCalledDefaultAndExportDefaultInteraction() {
Module test0 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportDefault(new FunctionDeclaration(new BindingIdentifier("*default*"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.nil())))));
assertCorrectFailures(test0, 0, "");
Module test1 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportDefault(new FunctionExpression(Maybe.just(new BindingIdentifier("*default*")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.nil())))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.BINDING_IDENTIFIERS_CALLED_DEFAULT);
Module test2 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportDefault(new ClassDeclaration(new BindingIdentifier("*default*"), Maybe.nothing(), ImmutableList.nil()))));
assertCorrectFailures(test2, 0, "");
Module test3 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportDefault(new ClassExpression(Maybe.just(new BindingIdentifier("*default*")), Maybe.nothing(), ImmutableList.nil()))));
assertCorrectFailures(test3, 1, ValidationErrorMessages.BINDING_IDENTIFIERS_CALLED_DEFAULT);
}
@Test
public void testReturnStatementAndFunctionBodyInteraction() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.nothing())));
assertCorrectFailures(test0, 1, ValidationErrorMessages.RETURN_STATEMENT_IN_FUNCTION_BODY);
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.just(new IdentifierExpression("a")))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.RETURN_STATEMENT_IN_FUNCTION_BODY);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.nothing()))))));
assertCorrectFailures(test2, 0 , "");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.just(new ThisExpression())))))));
assertCorrectFailures(test3, 0 , "");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.nothing())))))));
assertCorrectFailures(test4, 0 , "");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.just(new ThisExpression()))))))));
assertCorrectFailures(test5, 0 , "");
}
@Test
public void testYieldExpressionAndFunctionDeclarationFunctionExpressionMethodInteraction() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new IdentifierExpression("a"))))));
assertCorrectFailures(test0, 1, ValidationErrorMessages.VALID_YIELD_EXPRESSION_POSITION);
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing()))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_YIELD_EXPRESSION_POSITION);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing())))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_YIELD_EXPRESSION_POSITION);
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing()))))))));
assertCorrectFailures(test3, 1, ValidationErrorMessages.VALID_YIELD_EXPRESSION_POSITION);
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing())))), new StaticPropertyName("a")))))));
assertCorrectFailures(test4, 1, ValidationErrorMessages.VALID_YIELD_EXPRESSION_POSITION);
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression()))))))));
assertCorrectFailures(test5, 1, ValidationErrorMessages.VALID_YIELD_EXPRESSION_POSITION);
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression())))))))));
assertCorrectFailures(test6, 1, ValidationErrorMessages.VALID_YIELD_EXPRESSION_POSITION);
Script test7 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression()))))), new StaticPropertyName("a")))))));
assertCorrectFailures(test7, 1, ValidationErrorMessages.VALID_YIELD_EXPRESSION_POSITION);
Script test8 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing())))))));
assertCorrectFailures(test8, 0, "");
Script test9 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing()))))))));
assertCorrectFailures(test9, 0, "");
Script test10 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing())))), new StaticPropertyName("a")))))));
assertCorrectFailures(test10, 0, "");
Script test11 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression()))))))));
assertCorrectFailures(test11, 0, "");
Script test12 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression())))))))));
assertCorrectFailures(test12, 0, "");
Script test13 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression()))))), new StaticPropertyName("a")))))));
assertCorrectFailures(test13, 0, "");
}
@Test
public void testYieldGeneratorExpressionAndFunctionDeclarationFunctionExpressionMethodInteraction() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new IdentifierExpression("a")))));
assertCorrectFailures(test0, 1, ValidationErrorMessages.VALID_YIELD_GENERATOR_EXPRESSION_POSITION);
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression())))))));
assertCorrectFailures(test1, 1, ValidationErrorMessages.VALID_YIELD_GENERATOR_EXPRESSION_POSITION);
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression()))))))));
assertCorrectFailures(test2, 1, ValidationErrorMessages.VALID_YIELD_GENERATOR_EXPRESSION_POSITION);
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression())))), new StaticPropertyName("a")))))));
assertCorrectFailures(test3, 1, ValidationErrorMessages.VALID_YIELD_GENERATOR_EXPRESSION_POSITION);
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression())))))));
assertCorrectFailures(test4, 0, "");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression()))))))));
assertCorrectFailures(test5, 0, "");
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression())))), new StaticPropertyName("a")))))));
assertCorrectFailures(test6, 0, "");
}
}
| src/test/java/com/shapesecurity/shift/validator/UnitTest.java | /*
* Copyright 2014 Shape Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.shapesecurity.shift.validator;
import com.shapesecurity.functional.data.ImmutableList;
import com.shapesecurity.functional.data.Maybe;
import com.shapesecurity.shift.ast.*;
import com.shapesecurity.shift.parser.JsError;
import com.shapesecurity.shift.parser.Parser;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UnitTest {
private void assertCorrectFailures(Script script, int expectedNumErrors, String expectedErrorMsg) {
ImmutableList<ValidationError> errors = Validator.validate(script);
assertEquals(expectedNumErrors, errors.length);
for (ValidationError error : errors) {
assertEquals(error.message, expectedErrorMsg);
}
}
private void assertCorrectFailures(Module module, int expectedNumErrors, String expectedErrorMsg) {
ImmutableList<ValidationError> errors = Validator.validate(module);
assertEquals(expectedNumErrors, errors.length);
for (ValidationError error : errors) {
assertEquals(error.message, expectedErrorMsg);
}
}
@Test
public void testBindingIdentifier() throws JsError {
Script test0 = Parser.parseScript("x=1");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new AssignmentExpression(new BindingIdentifier("1"), new LiteralNumericExpression(0.0)))));
assertCorrectFailures(test1, 1, "the name field of binding identifier must be a valid identifier name");
}
@Test
public void testBreakStatement() throws JsError {
Script test0 = Parser.parseScript("for(var i = 0; i < 10; i++) { break; }");
assertCorrectFailures(test0, 0, "");
Script test1 = Parser.parseScript("done: while (true) { break done; }");
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("done", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new BreakStatement(Maybe.just("1done")))))))));
assertCorrectFailures(test2, 1, "the label field of break statement exists and must be a valid identifier name");
}
@Test
public void testCatchClause() throws JsError {
Script test0 = Parser.parseScript("try{} catch(e){} finally{}");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new TryFinallyStatement(new Block(ImmutableList.nil()), Maybe.just(new CatchClause(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), new Block(ImmutableList.nil()))), new Block(ImmutableList.nil()))));
assertCorrectFailures(test1, 1, "the binding field of CatchClause must not be a member expression");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new TryFinallyStatement(new Block(ImmutableList.nil()), Maybe.just(new CatchClause(new StaticMemberExpression("a", new IdentifierExpression("b")), new Block(ImmutableList.nil()))), new Block(ImmutableList.nil()))));
assertCorrectFailures(test2, 1, "the binding field of CatchClause must not be a member expression");
}
@Test
public void testContinueStatement() throws JsError {
Script test0 = Parser.parseScript("for(var i = 0; i < 10; i++) { continue; }");
assertCorrectFailures(test0, 0, "");
Script test1 = Parser.parseScript("done: while (true) { continue done; }");
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("done", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new ContinueStatement(Maybe.just("1done")))))))));
assertCorrectFailures(test2, 1, "the label field of continue statement exists and must be a valid identifier name");
}
@Test
public void testDirective() {
Script test0 = new Script(ImmutableList.list(new Directive("use strict;"), new Directive("linda;"), new Directive(".-#($*&#")), ImmutableList.nil());
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.list(new Directive("'use strict;")), ImmutableList.nil());
assertCorrectFailures(test1, 1, "the raw value field of directives must either be an empty string, or match the ES6 grammar production DoubleStringCharacter or SingleStringCharacter");
Script test2 = new Script(ImmutableList.list(new Directive("'use strict;"), new Directive("linda';"), new Directive("'.-#($*&#")), ImmutableList.nil());
assertCorrectFailures(test2, 3, "the raw value field of directives must either be an empty string, or match the ES6 grammar production DoubleStringCharacter or SingleStringCharacter");
Script test3 = new Script(ImmutableList.list(new Directive("'use stri\"ct;"), new Directive("li\"nda;'"), new Directive(".-\"#'($*&#")), ImmutableList.nil());
assertCorrectFailures(test3, 3, "the raw value field of directives must either be an empty string, or match the ES6 grammar production DoubleStringCharacter or SingleStringCharacter");
Script test4 = new Script(ImmutableList.list(new Directive("'use s\ntrict;"), new Directive("lind\na;'"), new Directive(".-#'($\n*&#")), ImmutableList.nil());
assertCorrectFailures(test4, 3, "the raw value field of directives must either be an empty string, or match the ES6 grammar production DoubleStringCharacter or SingleStringCharacter");
Script test5 = new Script(ImmutableList.list(new Directive("'use s\rtrict;"), new Directive("lind\ra;'"), new Directive(".-#'($\r*&#")), ImmutableList.nil());
assertCorrectFailures(test5, 3, "the raw value field of directives must either be an empty string, or match the ES6 grammar production DoubleStringCharacter or SingleStringCharacter");
Script test6 = new Script(ImmutableList.list(new Directive("('\\x0');"), new Directive("('\u2028')"), new Directive("(\\u{110000}\\\")")), ImmutableList.nil());
assertCorrectFailures(test6, 3, "the raw value field of directives must either be an empty string, or match the ES6 grammar production DoubleStringCharacter or SingleStringCharacter");
}
@Test
public void testExportSpecifier() throws JsError {
Module test0 = Parser.parseModule("export * from 'a';");
assertCorrectFailures(test0, 0, "");
Module test1 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportFrom(ImmutableList.list(new ExportSpecifier(Maybe.just("2a_"), "b")), Maybe.just("a"))));
assertCorrectFailures(test1, 1, "the name field of export specifier exists and must be a valid identifier name");
Module test2 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportFrom(ImmutableList.list(new ExportSpecifier(Maybe.just("b"), "%dlk45")), Maybe.just("a"))));
assertCorrectFailures(test2, 1, "the exported name field of export specifier must be a valid identifier name");
Module test3 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportFrom(ImmutableList.list(new ExportSpecifier(Maybe.nothing(), "a")), Maybe.just("a"))));
assertCorrectFailures(test3, 0, "");
}
@Test
public void testForInStatement() throws JsError {
Script test0 = Parser.parseScript("for (var x in [1,2,3]){}");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test1, 1, "VariableDeclaration in ForInStatement can only have one VariableDeclarator");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test2, 1, "VariableDeclaration in ForInStatement can only have one VariableDeclarator");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test3, 1, "VariableDeclaration in ForInStatement can only have one VariableDeclarator");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test4, 1, "The VariableDeclarator in ForInStatement should not have an initializer");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test5, 1, "The VariableDeclarator in ForInStatement should not have an initializer");
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new ForInStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test6, 1, "The VariableDeclarator in ForInStatement should not have an initializer");
}
@Test
public void testForOfStatement() throws JsError {
Script test0 = Parser.parseScript("for (var x of [1,2,3]){}");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test1, 1, "VariableDeclaration in ForOfStatement can only have one VariableDeclarator");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test2, 1, "VariableDeclaration in ForOfStatement can only have one VariableDeclarator");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()), new VariableDeclarator(new BindingIdentifier("b"), Maybe.nothing()))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test3, 1, "VariableDeclaration in ForOfStatement can only have one VariableDeclarator");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test4, 1, "The VariableDeclarator in ForOfStatement should not have an initializer");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test5, 1, "The VariableDeclarator in ForOfStatement should not have an initializer");
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new ForOfStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))), new ArrayExpression(ImmutableList.list(Maybe.just(new LiteralNumericExpression(0.0)), Maybe.just(new LiteralNumericExpression(1.0)))), new EmptyStatement())));
assertCorrectFailures(test6, 1, "The VariableDeclarator in ForOfStatement should not have an initializer");
}
@Test
public void testFormalParameters() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new BindingIdentifier("a")), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test2, 1, "the items field of formal parameters must not be member expressions");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new StaticMemberExpression("a", new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test3, 1, "the items field of formal parameters must not be member expressions");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new BindingWithDefault(new BindingIdentifier("a"), new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test4, 0, "");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new BindingWithDefault(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test5, 1, "binding field of the items field of formal parameters must not be a member expression");
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("hello"), false, new FormalParameters(ImmutableList.list(new BindingWithDefault(new StaticMemberExpression("a", new IdentifierExpression("b")), new IdentifierExpression("b"))), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new CallExpression(new IdentifierExpression("z"), ImmutableList.nil())))))));
assertCorrectFailures(test6, 1, "binding field of the items field of formal parameters must not be a member expression");
}
@Test
public void testIdentifierExpression() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("linda"))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("9458723"))));
assertCorrectFailures(test1, 1, "the name field of identifier expression must be a valid identifier name");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("A*9458723"))));
assertCorrectFailures(test2, 1, "the name field of identifier expression must be a valid identifier name");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("0lkdjaf"))));
assertCorrectFailures(test3, 1, "the name field of identifier expression must be a valid identifier name");
}
@Test
public void testIfStatement() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new IfStatement(new ThisExpression(), new ExpressionStatement(new ThisExpression()), Maybe.just(new ExpressionStatement(new ThisExpression())))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new IfStatement(new IdentifierExpression("a"), new ExpressionStatement(new IdentifierExpression("b")), Maybe.nothing())));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new IfStatement(new IdentifierExpression("a"), new IfStatement(new ThisExpression(), new ExpressionStatement(new ThisExpression()), Maybe.nothing()), Maybe.just(new ExpressionStatement(new ThisExpression())))));
assertCorrectFailures(test2, 1, "IfStatement with null 'alternate' must not be the 'consequent' of an IfStatement with a non-null 'alternate'");
}
@Test
public void testImportSpecifier() {
Module test0 = new Module(ImmutableList.nil(), ImmutableList.list(new Import(Maybe.just(new BindingIdentifier("a")), ImmutableList.list(new ImportSpecifier(Maybe.nothing(), new BindingIdentifier("b"))), "c")));
assertCorrectFailures(test0, 0, "");
Module test1 = new Module(ImmutableList.nil(), ImmutableList.list(new Import(Maybe.just(new BindingIdentifier("a")), ImmutableList.list(new ImportSpecifier(Maybe.just("a"), new BindingIdentifier("b"))), "c")));
assertCorrectFailures(test1, 0, "");
Module test2 = new Module(ImmutableList.nil(), ImmutableList.list(new Import(Maybe.just(new BindingIdentifier("a")), ImmutableList.list(new ImportSpecifier(Maybe.just("2d849"), new BindingIdentifier("b"))), "c")));
assertCorrectFailures(test2, 1, "the name field of import specifier exists and must be a valid identifier name");
}
@Test
public void testLabeledStatement() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("done", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new BreakStatement(Maybe.just("done")))))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("5346done", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new BreakStatement(Maybe.just("done")))))))));
assertCorrectFailures(test1, 1, "the label field of labeled statement must be a valid identifier name");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new LabeledStatement("#das*($839da", new WhileStatement(new LiteralBooleanExpression(true), new BlockStatement(new Block(ImmutableList.list(new ContinueStatement(Maybe.just("done")))))))));
assertCorrectFailures(test2, 1, "the label field of labeled statement must be a valid identifier name");
}
@Test
public void testLiteralNumericExpression() throws JsError {
Script test0 = Parser.parseScript("1.0");
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralNumericExpression(-1.0))));
assertCorrectFailures(test1, 1, "the value field of literal numeric expression must be non-negative");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralNumericExpression(1.0/0))));
assertCorrectFailures(test2, 1, "the value field of literal numeric expression must be finite");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralNumericExpression(Double.NaN))));
assertCorrectFailures(test3, 1, "the value field of literal numeric expression must not be NaN");
}
@Test
public void testLiteralRegExpExpression() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralRegExpExpression("@", ""))));
assertCorrectFailures(test0, 1, "pattern field of literal regular expression expression must match the ES6 grammar production Pattern (21.2.1)");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralRegExpExpression("/a/", "j"))));
assertCorrectFailures(test1, 1, "flags field of literal regular expression expression must not contain characters other than 'g', 'i', 'm', 'u', or 'y'");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new LiteralRegExpExpression("/a/", "gg"))));
assertCorrectFailures(test2, 1, "flags field of literal regular expression expression must not contain duplicate flag characters");
}
@Test
public void testSetter() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new BindingIdentifier("w"), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test1, 1, "the param field of setter must not be a member expression");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new StaticMemberExpression("a", new IdentifierExpression("b")), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test2, 1, "the param field of setter must not be a member expression");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new BindingWithDefault(new BindingIdentifier("a"), new LiteralNumericExpression(0.0)), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test3, 0, "");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new BindingWithDefault(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), new LiteralNumericExpression(0.0)), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test4, 1, "the binding field of the param field of setter must not be a member expression");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Setter(new BindingWithDefault(new StaticMemberExpression("a", new IdentifierExpression("b")), new LiteralNumericExpression(0.0)), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new IdentifierExpression("w")))), new StaticPropertyName("width")))))));
assertCorrectFailures(test5, 1, "the binding field of the param field of setter must not be a member expression");
}
@Test
public void testShorthandProperty() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new ShorthandProperty("a"), new ShorthandProperty("asajd_nk"))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new ShorthandProperty("429adk"), new ShorthandProperty("asajd_nk"))))));
assertCorrectFailures(test1, 1, "the name field of shorthand property must be a valid identifier name");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new ShorthandProperty("a"), new ShorthandProperty("^34d9"))))));
assertCorrectFailures(test2, 1, "the name field of shorthand property must be a valid identifier name");
}
@Test
public void testStaticMemberExpression() throws JsError {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new StaticMemberExpression("b", new IdentifierExpression("a")))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new StaticMemberExpression("45829", new IdentifierExpression("a")))));
assertCorrectFailures(test1, 1, "the property field of static member expression must be a valid identifier name");
}
@Test
public void testTemplateElement() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("abc"))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("\"abc'"))))));
assertCorrectFailures(test1, 1, "the raw value field of template element must match the ES6 grammar production TemplateCharacters");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("'abc\""))))));
assertCorrectFailures(test2, 1, "the raw value field of template element must match the ES6 grammar production TemplateCharacters");
}
@Test
public void testTemplateExpression() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("a"), new IdentifierExpression("b"), new TemplateElement("c"))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new IdentifierExpression("b"), new TemplateElement("c"))))));
assertCorrectFailures(test1, 1, "the elements field of template expression must be an alternating list of template element and expression, starting and ending with a template element");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new TemplateElement("a"), new IdentifierExpression("b"), new TemplateElement("c"), new TemplateElement("c"), new TemplateElement("c"))))));
assertCorrectFailures(test2, 1, "the elements field of template expression must be an alternating list of template element and expression, starting and ending with a template element");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new TemplateExpression(Maybe.nothing(), ImmutableList.list(new IdentifierExpression("b"), new TemplateElement("c"), new IdentifierExpression("b"))))));
assertCorrectFailures(test3, 3, "the elements field of template expression must be an alternating list of template element and expression, starting and ending with a template element");
}
@Test
public void testVariableDeclaration() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test2, 0, "");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list()))));
assertCorrectFailures(test3, 1, "the declarators field in variable declaration must not be an empty list");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list()))));
assertCorrectFailures(test4, 1, "the declarators field in variable declaration must not be an empty list");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list()))));
assertCorrectFailures(test5, 1, "the declarators field in variable declaration must not be an empty list");
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.nil()))));
assertCorrectFailures(test6, 1, "the declarators field in variable declaration must not be an empty list");
Script test7 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.nil()))));
assertCorrectFailures(test7, 1, "the declarators field in variable declaration must not be an empty list");
Script test8 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.nil()))));
assertCorrectFailures(test8, 1, "the declarators field in variable declaration must not be an empty list");
}
@Test
public void testVariableDeclarationStatement() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test2, 0, "");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()))))));
assertCorrectFailures(test3, 0, "");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()))))));
assertCorrectFailures(test4, 0, "");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.nothing()))))));
assertCorrectFailures(test5, 1, "VariableDeclarationStatements with a variable declaration of kind const cannot have a variable declarator with no initializer");
}
@Test
public void testVariableDeclarator() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test0, 0, "");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test1, 0, "");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new BindingIdentifier("a"), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test2, 0, "");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test3, 1, "the binding field of variable declarator must not be a member expression");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Var, ImmutableList.list(new VariableDeclarator(new StaticMemberExpression("a", new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test4, 1, "the binding field of variable declarator must not be a member expression");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test5, 1, "the binding field of variable declarator must not be a member expression");
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Let, ImmutableList.list(new VariableDeclarator(new StaticMemberExpression("a", new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test6, 1, "the binding field of variable declarator must not be a member expression");
Script test7 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new ComputedMemberExpression(new IdentifierExpression("a"), new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test7, 1, "the binding field of variable declarator must not be a member expression");
Script test8 = new Script(ImmutableList.nil(), ImmutableList.list(new VariableDeclarationStatement(new VariableDeclaration(VariableDeclarationKind.Const, ImmutableList.list(new VariableDeclarator(new StaticMemberExpression("a", new IdentifierExpression("b")), Maybe.just(new LiteralNumericExpression(0.0))))))));
assertCorrectFailures(test8, 1, "the binding field of variable declarator must not be a member expression");
}
@Test
public void testBindingIdentifierCalledDefaultAndExportDefaultInteraction() {
Module test0 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportDefault(new FunctionDeclaration(new BindingIdentifier("*default*"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.nil())))));
assertCorrectFailures(test0, 0, "");
Module test1 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportDefault(new FunctionExpression(Maybe.just(new BindingIdentifier("*default*")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.nil())))));
assertCorrectFailures(test1, 1, "binding identifiers may only be called \"*default*\" within a function declaration or class declaration");
Module test2 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportDefault(new ClassDeclaration(new BindingIdentifier("*default*"), Maybe.nothing(), ImmutableList.nil()))));
assertCorrectFailures(test2, 0, "");
Module test3 = new Module(ImmutableList.nil(), ImmutableList.list(new ExportDefault(new ClassExpression(Maybe.just(new BindingIdentifier("*default*")), Maybe.nothing(), ImmutableList.nil()))));
assertCorrectFailures(test3, 1, "binding identifiers may only be called \"*default*\" within a function declaration or class declaration");
}
@Test
public void testReturnStatementAndFunctionBodyInteraction() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.nothing())));
assertCorrectFailures(test0, 1, "return statements must be within a function body");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.just(new IdentifierExpression("a")))));
assertCorrectFailures(test1, 1, "return statements must be within a function body");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.nothing()))))));
assertCorrectFailures(test2, 0 , "");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.just(new ThisExpression())))))));
assertCorrectFailures(test3, 0 , "");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.nothing())))))));
assertCorrectFailures(test4, 0 , "");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ReturnStatement(Maybe.just(new ThisExpression()))))))));
assertCorrectFailures(test5, 0 , "");
}
@Test
public void testYieldExpressionAndFunctionDeclarationFunctionExpressionMethodInteraction() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new IdentifierExpression("a"))))));
assertCorrectFailures(test0, 1, "yield expressions are only allowed within function declarations or function expressions that are generators");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing()))));
assertCorrectFailures(test1, 1, "yield expressions are only allowed within function declarations or function expressions that are generators");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing())))))));
assertCorrectFailures(test2, 1, "yield expressions are only allowed within function declarations or function expressions that are generators");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing()))))))));
assertCorrectFailures(test3, 1, "yield expressions are only allowed within function declarations or function expressions that are generators");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing())))), new StaticPropertyName("a")))))));
assertCorrectFailures(test4, 1, "yield expressions are only allowed within function declarations or function expressions that are generators");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression()))))))));
assertCorrectFailures(test5, 1, "yield expressions are only allowed within function declarations or function expressions that are generators");
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression())))))))));
assertCorrectFailures(test6, 1, "yield expressions are only allowed within function declarations or function expressions that are generators");
Script test7 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression()))))), new StaticPropertyName("a")))))));
assertCorrectFailures(test7, 1, "yield expressions are only allowed within function declarations or function expressions that are generators");
Script test8 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing())))))));
assertCorrectFailures(test8, 0, "");
Script test9 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing()))))))));
assertCorrectFailures(test9, 0, "");
Script test10 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.nothing())))), new StaticPropertyName("a")))))));
assertCorrectFailures(test10, 0, "");
Script test11 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression()))))))));
assertCorrectFailures(test11, 0, "");
Script test12 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression())))))))));
assertCorrectFailures(test12, 0, "");
Script test13 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldExpression(Maybe.just(new ThisExpression()))))), new StaticPropertyName("a")))))));
assertCorrectFailures(test13, 0, "");
}
@Test
public void testYieldGeneratorExpressionAndFunctionDeclarationFunctionExpressionMethodInteraction() {
Script test0 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new IdentifierExpression("a")))));
assertCorrectFailures(test0, 1, "yield generator expressions are only allowed within function declarations or function expressions that are generators");
Script test1 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression())))))));
assertCorrectFailures(test1, 1, "yield generator expressions are only allowed within function declarations or function expressions that are generators");
Script test2 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression()))))))));
assertCorrectFailures(test2, 1, "yield generator expressions are only allowed within function declarations or function expressions that are generators");
Script test3 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(false, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression())))), new StaticPropertyName("a")))))));
assertCorrectFailures(test3, 1, "yield generator expressions are only allowed within function declarations or function expressions that are generators");
Script test4 = new Script(ImmutableList.nil(), ImmutableList.list(new FunctionDeclaration(new BindingIdentifier("a"), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression())))))));
assertCorrectFailures(test4, 0, "");
Script test5 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new FunctionExpression(Maybe.just(new BindingIdentifier("a")), true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression()))))))));
assertCorrectFailures(test5, 0, "");
Script test6 = new Script(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new ObjectExpression(ImmutableList.list(new Method(true, new FormalParameters(ImmutableList.nil(), Maybe.nothing()), new FunctionBody(ImmutableList.nil(), ImmutableList.list(new ExpressionStatement(new YieldGeneratorExpression(new ThisExpression())))), new StaticPropertyName("a")))))));
assertCorrectFailures(test6, 0, "");
}
}
| fixed validator unit tests to use error message constants. all tests now pass
| src/test/java/com/shapesecurity/shift/validator/UnitTest.java | fixed validator unit tests to use error message constants. all tests now pass |
|
Java | apache-2.0 | cc5cc593e09ceee1e333b8bb4297b1664d3c4115 | 0 | gaieepo/HubTurbo,saav/HubTurbo,gaieepo/HubTurbo,ianngiaw/HubTurbo,ianngiaw/HubTurbo,Sumei1009/HubTurbo,HyungJon/HubTurbo,saav/HubTurbo,Honoo/HubTurbo,Sumei1009/HubTurbo,HyungJon/HubTurbo,Honoo/HubTurbo | package ui;
import backend.Logic;
import backend.UIManager;
import browserview.BrowserComponent;
import browserview.BrowserComponentStub;
import com.google.common.eventbus.EventBus;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HWND;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import prefs.Preferences;
import ui.components.HTStatusBar;
import ui.components.KeyboardShortcuts;
import ui.components.StatusUI;
import ui.issuecolumn.ColumnControl;
import util.PlatformEx;
import util.PlatformSpecific;
import util.TickingTimer;
import util.Utility;
import util.events.*;
import util.events.Event;
import util.events.testevents.UILogicRefreshEventHandler;
import util.events.testevents.WindowResizeEvent;
import java.awt.*;
import java.util.HashMap;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
public class UI extends Application implements EventDispatcher {
private static final int VERSION_MAJOR = 2;
private static final int VERSION_MINOR = 9;
private static final int VERSION_PATCH = 0;
public static final String ARG_UPDATED_TO = "--updated-to";
private static final double WINDOW_DEFAULT_PROPORTION = 0.6;
private static final Logger logger = LogManager.getLogger(UI.class.getName());
private static HWND mainWindowHandle;
private static final int REFRESH_PERIOD = 60;
// Application-level state
public UIManager uiManager;
public Logic logic;
public Preferences prefs;
public static StatusUI status;
public static EventDispatcher events;
public EventBus eventBus;
private HashMap<String, String> commandLineArgs;
private TickingTimer refreshTimer;
// Main UI elements
private Stage mainStage;
private ColumnControl columns;
private MenuControl menuBar;
private BrowserComponent browserComponent;
private RepositorySelector repoSelector;
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage stage) {
initPreApplicationState();
initUI(stage);
initApplicationState();
getUserCredentials();
}
private void getUserCredentials() {
if (isBypassLogin()) {
showMainWindow("dummy/dummy");
mainStage.show();
} else {
disableUI(true);
mainStage.show();
new LoginDialog(this, prefs, mainStage).setup().thenApply(result -> {
if (result.success) {
showMainWindow(result.repoId);
disableUI(false);
} else {
quit();
}
return true;
}).exceptionally(e -> {
logger.error(e.getLocalizedMessage(), e);
return false;
});
}
}
private void disableUI(boolean disable) {
mainStage.setResizable(!disable);
menuBar.setDisable(disable);
repoSelector.setDisable(disable);
}
private void showMainWindow(String repoId) {
logic.openRepository(repoId);
logic.setDefaultRepo(repoId);
repoSelector.setText(repoId);
triggerEvent(new BoardSavedEvent()); // Initializes boards
if (isTestMode()) {
if (isTestChromeDriver()) {
browserComponent = new BrowserComponent(this, true);
browserComponent.initialise();
} else {
browserComponent = new BrowserComponentStub(this);
}
registerTestEvents();
} else {
browserComponent = new BrowserComponent(this, false);
browserComponent.initialise();
}
setExpandedWidth(false);
columns.init();
// Should only be called after columns have been initialized
ensureSelectedPanelHasFocus();
}
private void registerTestEvents() {
registerEvent((UILogicRefreshEventHandler) e -> Platform.runLater(logic::refresh));
}
private void initPreApplicationState() {
logger.info(Utility.version(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH));
UI.events = this;
Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) ->
logger.error(throwable.getMessage(), throwable));
commandLineArgs = initialiseCommandLineArguments();
prefs = new Preferences(isTestMode());
KeyboardShortcuts.loadKeyboardShortcuts(prefs);
eventBus = new EventBus();
registerEvent((RepoOpenedEventHandler) e -> onRepoOpened());
uiManager = new UIManager(this);
status = new HTStatusBar(this);
}
private void initApplicationState() {
// In the future, when more arguments are passed to logic,
// we can pass them in the form of an array.
logic = new Logic(uiManager, prefs, isTestMode(), isTestJSONEnabled());
clearCacheIfNecessary();
refreshTimer = new TickingTimer("Refresh Timer", REFRESH_PERIOD,
status::updateTimeToRefresh, logic::refresh, TimeUnit.SECONDS);
refreshTimer.start();
}
private void initUI(Stage stage) {
repoSelector = createRepoSelector();
mainStage = stage;
stage.setMaximized(false);
Scene scene = new Scene(createRoot());
setupMainStage(scene);
loadFonts();
String css = initCSS();
applyCSS(css, scene);
}
// Test mode should only be run as a test task (Gradle / JUnit), as quit()
// leaves the JVM alive during test mode (which is cleaned up by Gradle).
// Manually feeding --test=true into the command line arguments will leave the JVM
// running after the HT window has been closed, and thus will require the
// process to be closed manually afterwards (Force Quit / End Process).
public boolean isTestMode() {
return commandLineArgs.getOrDefault("test", "false").equalsIgnoreCase("true") ||
isBypassLogin() ||
isTestJSONEnabled() ||
isTestChromeDriver() ||
isTestGlobalConfig();
}
// Public for use in LoginDialog
public boolean isTestGlobalConfig() {
return commandLineArgs.getOrDefault("testconfig", "false").equalsIgnoreCase("true");
}
// When --bypasslogin=true is passed as an argument, the username and password
// are empty strings.
private boolean isBypassLogin() {
return commandLineArgs.getOrDefault("bypasslogin", "false").equalsIgnoreCase("true");
}
private boolean isTestJSONEnabled() {
return commandLineArgs.getOrDefault("testjson", "false").equalsIgnoreCase("true");
}
private boolean isTestChromeDriver() {
return commandLineArgs.getOrDefault("testchromedriver", "false").equalsIgnoreCase("true");
}
public void quit() {
if (browserComponent != null) {
browserComponent.onAppQuit();
}
if (!isTestMode()) {
columns.saveSession();
prefs.saveGlobalConfig();
Platform.exit();
System.exit(0);
}
if (isTestGlobalConfig()) {
columns.saveSession();
prefs.saveGlobalConfig();
}
}
public void onRepoOpened() {
repoSelector.refreshContents();
}
/**
* TODO Stop-gap measure pending a more robust updater
*/
private void clearCacheIfNecessary() {
if (getCommandLineArgs().containsKey(ARG_UPDATED_TO)) {
// TODO
// CacheFileHandler.deleteCacheDirectory();
}
}
public String initCSS() {
return getClass().getResource("hubturbo.css").toString();
}
public static void applyCSS(String css, Scene scene) {
scene.getStylesheets().clear();
scene.getStylesheets().add(css);
}
public static void loadFonts(){
Font.loadFont(UI.class.getResource("octicons/octicons-local.ttf").toExternalForm(), 32);
}
private void setupMainStage(Scene scene) {
mainStage.setTitle("HubTurbo " + Utility.version(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH));
mainStage.setScene(scene);
mainStage.show();
mainStage.setOnCloseRequest(e -> quit());
initialiseJNA(mainStage.getTitle());
mainStage.focusedProperty().addListener((unused, wasFocused, isFocused) -> {
if (!isFocused) {
return;
}
if (PlatformSpecific.isOnWindows()) {
browserComponent.focus(mainWindowHandle);
}
PlatformEx.runLaterDelayed(() -> {
if (browserComponent != null) {
boolean shouldRefresh = browserComponent.hasBviewChanged();
if (shouldRefresh) {
logger.info("Browser view has changed; refreshing");
logic.refresh();
refreshTimer.restart();
}
}
});
});
mainStage.hide();
}
private static void initialiseJNA(String windowTitle) {
if (PlatformSpecific.isOnWindows()) {
mainWindowHandle = User32.INSTANCE.FindWindow(null, windowTitle);
}
}
private HashMap<String, String> initialiseCommandLineArguments() {
Parameters params = getParameters();
return new HashMap<>(params.getNamed());
}
private Parent createRoot() {
columns = new ColumnControl(this, prefs);
VBox top = new VBox();
ScrollPane columnsScrollPane = new ScrollPane(columns);
columnsScrollPane.getStyleClass().add("transparent-bg");
columnsScrollPane.setFitToHeight(true);
columnsScrollPane.setVbarPolicy(ScrollBarPolicy.NEVER);
HBox.setHgrow(columnsScrollPane, Priority.ALWAYS);
menuBar = new MenuControl(this, columns, columnsScrollPane, prefs);
top.getChildren().addAll(menuBar, repoSelector);
BorderPane root = new BorderPane();
root.setTop(top);
root.setCenter(columnsScrollPane);
root.setBottom((HTStatusBar) status);
return root;
}
/**
* Sets the dimensions of the stage to the maximum usable size
* of the desktop, or to the screen size if this fails.
*/
private Rectangle getDimensions() {
Optional<Rectangle> dimensions = Utility.getUsableScreenDimensions();
if (dimensions.isPresent()) {
return dimensions.get();
} else {
return Utility.getScreenDimensions();
}
}
/**
* UI operations
*/
@Override
public void registerEvent(EventHandler handler) {
eventBus.register(handler);
logger.info("Registered event handler " + handler.getClass().getInterfaces()[0].getSimpleName());
}
@Override
public void unregisterEvent(EventHandler handler) {
eventBus.unregister(handler);
logger.info("Unregistered event handler " + handler.getClass().getInterfaces()[0].getSimpleName());
}
@Override
public <T extends Event> void triggerEvent(T event) {
logger.info("About to trigger event " + event.getClass().getSimpleName());
eventBus.post(event);
logger.info("Triggered event " + event.getClass().getSimpleName());
}
public BrowserComponent getBrowserComponent() {
return browserComponent;
}
/**
* Returns the X position of the edge of the collapsed window.
* This function may be called before the main stage is initialised, in
* which case it simply returns a reasonable default.
*/
public double getCollapsedX() {
if (mainStage == null) {
return getDimensions().getWidth() * WINDOW_DEFAULT_PROPORTION;
}
return mainStage.getWidth();
}
/**
* Returns the dimensions of the screen available for use when
* the main window is in a collapsed state.
* This function may be called before the main stage is initialised, in
* which case it simply returns a reasonable default.
*/
public Rectangle getAvailableDimensions() {
Rectangle dimensions = getDimensions();
if (mainStage == null) {
return new Rectangle(
(int) (dimensions.getWidth() * WINDOW_DEFAULT_PROPORTION),
(int) dimensions.getHeight());
}
return new Rectangle(
(int) (dimensions.getWidth() - mainStage.getWidth()),
(int) dimensions.getHeight());
}
/**
* Controls whether or not the main window is expanded (occupying the
* whole screen) or not (occupying a percentage).
* @param expanded
*/
private void setExpandedWidth(boolean expanded) {
Rectangle dimensions = getDimensions();
double width = expanded
? dimensions.getWidth()
: dimensions.getWidth() * WINDOW_DEFAULT_PROPORTION;
mainStage.setMinWidth(columns.getPanelWidth());
mainStage.setMinHeight(dimensions.getHeight());
mainStage.setMaxWidth(width);
mainStage.setMaxHeight(dimensions.getHeight());
mainStage.setX(0);
mainStage.setY(0);
mainStage.setMaxWidth(dimensions.getWidth());
}
public HashMap<String, String> getCommandLineArgs() {
return commandLineArgs;
}
private RepositorySelector createRepoSelector() {
RepositorySelector repoSelector = new RepositorySelector(this);
repoSelector.setOnValueChange(this::primaryRepoChanged);
return repoSelector;
}
private void primaryRepoChanged(String repoId) {
logic.openRepository(repoId);
logic.setDefaultRepo(repoId);
repoSelector.setText(repoId);
columns.refresh();
}
private void ensureSelectedPanelHasFocus() {
if (columns.getCurrentlySelectedColumn().isPresent()) {
getMenuControl().scrollTo(
columns.getCurrentlySelectedColumn().get(),
columns.getChildren().size());
columns.getColumn(columns.getCurrentlySelectedColumn().get()).requestFocus();
}
}
public MenuControl getMenuControl() {
return menuBar;
}
public void setDefaultWidth() {
if (isTestMode()) {
triggerEvent(new WindowResizeEvent(WindowResizeEvent.EventType.DEFAULT_SIZE_WINDOW));
}
mainStage.setMaximized(false);
Rectangle dimensions = getDimensions();
mainStage.setMinWidth(columns.getPanelWidth());
mainStage.setMinHeight(dimensions.getHeight());
mainStage.setMaxWidth(columns.getPanelWidth());
mainStage.setMaxHeight(dimensions.getHeight());
mainStage.setX(0);
mainStage.setY(0);
}
public void maximizeWindow() {
if (isTestMode()) {
triggerEvent(new WindowResizeEvent(WindowResizeEvent.EventType.MAXIMIZE_WINDOW));
}
mainStage.setMaximized(true);
Rectangle dimensions = getDimensions();
mainStage.setMinWidth(dimensions.getWidth());
mainStage.setMinHeight(dimensions.getHeight());
mainStage.setMaxWidth(dimensions.getWidth());
mainStage.setMaxHeight(dimensions.getHeight());
mainStage.setX(0);
mainStage.setY(0);
}
public void minimizeWindow() {
if (isTestMode()) {
triggerEvent(new WindowResizeEvent(WindowResizeEvent.EventType.MINIMIZE_WINDOW));
}
mainStage.setIconified(true);
menuBar.scrollTo(columns.getCurrentlySelectedColumn().get(), columns.getChildren().size());
}
public HWND getMainWindowHandle() {
return mainWindowHandle;
}
}
| src/main/java/ui/UI.java | package ui;
import backend.Logic;
import backend.UIManager;
import browserview.BrowserComponent;
import browserview.BrowserComponentStub;
import com.google.common.eventbus.EventBus;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HWND;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import prefs.Preferences;
import ui.components.HTStatusBar;
import ui.components.KeyboardShortcuts;
import ui.components.StatusUI;
import ui.issuecolumn.ColumnControl;
import util.PlatformEx;
import util.PlatformSpecific;
import util.TickingTimer;
import util.Utility;
import util.events.*;
import util.events.Event;
import util.events.testevents.UILogicRefreshEventHandler;
import util.events.testevents.WindowResizeEvent;
import java.awt.*;
import java.util.HashMap;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
public class UI extends Application implements EventDispatcher {
private static final int VERSION_MAJOR = 2;
private static final int VERSION_MINOR = 9;
private static final int VERSION_PATCH = 0;
public static final String ARG_UPDATED_TO = "--updated-to";
private static final double WINDOW_DEFAULT_PROPORTION = 0.6;
private static final Logger logger = LogManager.getLogger(UI.class.getName());
private static HWND mainWindowHandle;
private static final int REFRESH_PERIOD = 60;
// Application-level state
public UIManager uiManager;
public Logic logic;
public Preferences prefs;
public static StatusUI status;
public static EventDispatcher events;
public EventBus eventBus;
private HashMap<String, String> commandLineArgs;
private TickingTimer refreshTimer;
// Main UI elements
private Stage mainStage;
private ColumnControl columns;
private MenuControl menuBar;
private BrowserComponent browserComponent;
private RepositorySelector repoSelector;
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage stage) {
initPreApplicationState();
initUI(stage);
initApplicationState();
getUserCredentials();
}
private void getUserCredentials() {
if (isBypassLogin()) {
showMainWindow("dummy/dummy");
} else {
new LoginDialog(this, prefs, mainStage).show().thenApply(result -> {
if (result.success) {
showMainWindow(result.repoId);
} else {
quit();
}
return true;
}).exceptionally(e -> {
logger.error(e.getLocalizedMessage(), e);
return false;
});
}
}
private void showMainWindow(String repoId) {
logic.openRepository(repoId);
logic.setDefaultRepo(repoId);
repoSelector.setText(repoId);
triggerEvent(new BoardSavedEvent()); // Initializes boards
if (isTestMode()) {
if (isTestChromeDriver()) {
browserComponent = new BrowserComponent(this, true);
browserComponent.initialise();
} else {
browserComponent = new BrowserComponentStub(this);
}
registerTestEvents();
} else {
browserComponent = new BrowserComponent(this, false);
browserComponent.initialise();
}
setExpandedWidth(false);
columns.init();
// Should only be called after columns have been initialized
ensureSelectedPanelHasFocus();
}
private void registerTestEvents() {
registerEvent((UILogicRefreshEventHandler) e -> Platform.runLater(logic::refresh));
}
private void initPreApplicationState() {
logger.info(Utility.version(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH));
UI.events = this;
Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) ->
logger.error(throwable.getMessage(), throwable));
commandLineArgs = initialiseCommandLineArguments();
prefs = new Preferences(isTestMode());
KeyboardShortcuts.loadKeyboardShortcuts(prefs);
eventBus = new EventBus();
registerEvent((RepoOpenedEventHandler) e -> onRepoOpened());
uiManager = new UIManager(this);
status = new HTStatusBar(this);
}
private void initApplicationState() {
// In the future, when more arguments are passed to logic,
// we can pass them in the form of an array.
logic = new Logic(uiManager, prefs, isTestMode(), isTestJSONEnabled());
clearCacheIfNecessary();
refreshTimer = new TickingTimer("Refresh Timer", REFRESH_PERIOD,
status::updateTimeToRefresh, logic::refresh, TimeUnit.SECONDS);
refreshTimer.start();
}
private void initUI(Stage stage) {
repoSelector = createRepoSelector();
mainStage = stage;
stage.setMaximized(false);
Scene scene = new Scene(createRoot());
setupMainStage(scene);
loadFonts();
String css = initCSS();
applyCSS(css, scene);
}
// Test mode should only be run as a test task (Gradle / JUnit), as quit()
// leaves the JVM alive during test mode (which is cleaned up by Gradle).
// Manually feeding --test=true into the command line arguments will leave the JVM
// running after the HT window has been closed, and thus will require the
// process to be closed manually afterwards (Force Quit / End Process).
public boolean isTestMode() {
return commandLineArgs.getOrDefault("test", "false").equalsIgnoreCase("true") ||
isBypassLogin() ||
isTestJSONEnabled() ||
isTestChromeDriver() ||
isTestGlobalConfig();
}
// Public for use in LoginDialog
public boolean isTestGlobalConfig() {
return commandLineArgs.getOrDefault("testconfig", "false").equalsIgnoreCase("true");
}
// When --bypasslogin=true is passed as an argument, the username and password
// are empty strings.
private boolean isBypassLogin() {
return commandLineArgs.getOrDefault("bypasslogin", "false").equalsIgnoreCase("true");
}
private boolean isTestJSONEnabled() {
return commandLineArgs.getOrDefault("testjson", "false").equalsIgnoreCase("true");
}
private boolean isTestChromeDriver() {
return commandLineArgs.getOrDefault("testchromedriver", "false").equalsIgnoreCase("true");
}
public void quit() {
if (browserComponent != null) {
browserComponent.onAppQuit();
}
if (!isTestMode()) {
columns.saveSession();
prefs.saveGlobalConfig();
Platform.exit();
System.exit(0);
}
if (isTestGlobalConfig()) {
columns.saveSession();
prefs.saveGlobalConfig();
}
}
public void onRepoOpened() {
repoSelector.refreshContents();
}
/**
* TODO Stop-gap measure pending a more robust updater
*/
private void clearCacheIfNecessary() {
if (getCommandLineArgs().containsKey(ARG_UPDATED_TO)) {
// TODO
// CacheFileHandler.deleteCacheDirectory();
}
}
public String initCSS() {
return getClass().getResource("hubturbo.css").toString();
}
public static void applyCSS(String css, Scene scene) {
scene.getStylesheets().clear();
scene.getStylesheets().add(css);
}
public static void loadFonts(){
Font.loadFont(UI.class.getResource("octicons/octicons-local.ttf").toExternalForm(), 32);
}
private void setupMainStage(Scene scene) {
mainStage.setTitle("HubTurbo " + Utility.version(VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH));
mainStage.setScene(scene);
mainStage.show();
mainStage.setOnCloseRequest(e -> quit());
initialiseJNA(mainStage.getTitle());
mainStage.focusedProperty().addListener((unused, wasFocused, isFocused) -> {
if (!isFocused) {
return;
}
if (PlatformSpecific.isOnWindows()) {
browserComponent.focus(mainWindowHandle);
}
PlatformEx.runLaterDelayed(() -> {
if (browserComponent != null) {
boolean shouldRefresh = browserComponent.hasBviewChanged();
if (shouldRefresh) {
logger.info("Browser view has changed; refreshing");
logic.refresh();
refreshTimer.restart();
}
}
});
});
}
private static void initialiseJNA(String windowTitle) {
if (PlatformSpecific.isOnWindows()) {
mainWindowHandle = User32.INSTANCE.FindWindow(null, windowTitle);
}
}
private HashMap<String, String> initialiseCommandLineArguments() {
Parameters params = getParameters();
return new HashMap<>(params.getNamed());
}
private Parent createRoot() {
columns = new ColumnControl(this, prefs);
VBox top = new VBox();
ScrollPane columnsScrollPane = new ScrollPane(columns);
columnsScrollPane.getStyleClass().add("transparent-bg");
columnsScrollPane.setFitToHeight(true);
columnsScrollPane.setVbarPolicy(ScrollBarPolicy.NEVER);
HBox.setHgrow(columnsScrollPane, Priority.ALWAYS);
menuBar = new MenuControl(this, columns, columnsScrollPane, prefs);
top.getChildren().addAll(menuBar, repoSelector);
BorderPane root = new BorderPane();
root.setTop(top);
root.setCenter(columnsScrollPane);
root.setBottom((HTStatusBar) status);
return root;
}
/**
* Sets the dimensions of the stage to the maximum usable size
* of the desktop, or to the screen size if this fails.
*/
private Rectangle getDimensions() {
Optional<Rectangle> dimensions = Utility.getUsableScreenDimensions();
if (dimensions.isPresent()) {
return dimensions.get();
} else {
return Utility.getScreenDimensions();
}
}
/**
* UI operations
*/
@Override
public void registerEvent(EventHandler handler) {
eventBus.register(handler);
logger.info("Registered event handler " + handler.getClass().getInterfaces()[0].getSimpleName());
}
@Override
public void unregisterEvent(EventHandler handler) {
eventBus.unregister(handler);
logger.info("Unregistered event handler " + handler.getClass().getInterfaces()[0].getSimpleName());
}
@Override
public <T extends Event> void triggerEvent(T event) {
logger.info("About to trigger event " + event.getClass().getSimpleName());
eventBus.post(event);
logger.info("Triggered event " + event.getClass().getSimpleName());
}
public BrowserComponent getBrowserComponent() {
return browserComponent;
}
/**
* Returns the X position of the edge of the collapsed window.
* This function may be called before the main stage is initialised, in
* which case it simply returns a reasonable default.
*/
public double getCollapsedX() {
if (mainStage == null) {
return getDimensions().getWidth() * WINDOW_DEFAULT_PROPORTION;
}
return mainStage.getWidth();
}
/**
* Returns the dimensions of the screen available for use when
* the main window is in a collapsed state.
* This function may be called before the main stage is initialised, in
* which case it simply returns a reasonable default.
*/
public Rectangle getAvailableDimensions() {
Rectangle dimensions = getDimensions();
if (mainStage == null) {
return new Rectangle(
(int) (dimensions.getWidth() * WINDOW_DEFAULT_PROPORTION),
(int) dimensions.getHeight());
}
return new Rectangle(
(int) (dimensions.getWidth() - mainStage.getWidth()),
(int) dimensions.getHeight());
}
/**
* Controls whether or not the main window is expanded (occupying the
* whole screen) or not (occupying a percentage).
* @param expanded
*/
private void setExpandedWidth(boolean expanded) {
Rectangle dimensions = getDimensions();
double width = expanded
? dimensions.getWidth()
: dimensions.getWidth() * WINDOW_DEFAULT_PROPORTION;
mainStage.setMinWidth(columns.getPanelWidth());
mainStage.setMinHeight(dimensions.getHeight());
mainStage.setMaxWidth(width);
mainStage.setMaxHeight(dimensions.getHeight());
mainStage.setX(0);
mainStage.setY(0);
mainStage.setMaxWidth(dimensions.getWidth());
}
public HashMap<String, String> getCommandLineArgs() {
return commandLineArgs;
}
private RepositorySelector createRepoSelector() {
RepositorySelector repoSelector = new RepositorySelector(this);
repoSelector.setOnValueChange(this::primaryRepoChanged);
return repoSelector;
}
private void primaryRepoChanged(String repoId) {
logic.openRepository(repoId);
logic.setDefaultRepo(repoId);
repoSelector.setText(repoId);
columns.refresh();
}
private void ensureSelectedPanelHasFocus() {
if (columns.getCurrentlySelectedColumn().isPresent()) {
getMenuControl().scrollTo(
columns.getCurrentlySelectedColumn().get(),
columns.getChildren().size());
columns.getColumn(columns.getCurrentlySelectedColumn().get()).requestFocus();
}
}
public MenuControl getMenuControl() {
return menuBar;
}
public void setDefaultWidth() {
if (isTestMode()) {
triggerEvent(new WindowResizeEvent(WindowResizeEvent.EventType.DEFAULT_SIZE_WINDOW));
}
mainStage.setMaximized(false);
Rectangle dimensions = getDimensions();
mainStage.setMinWidth(columns.getPanelWidth());
mainStage.setMinHeight(dimensions.getHeight());
mainStage.setMaxWidth(columns.getPanelWidth());
mainStage.setMaxHeight(dimensions.getHeight());
mainStage.setX(0);
mainStage.setY(0);
}
public void maximizeWindow() {
if (isTestMode()) {
triggerEvent(new WindowResizeEvent(WindowResizeEvent.EventType.MAXIMIZE_WINDOW));
}
mainStage.setMaximized(true);
Rectangle dimensions = getDimensions();
mainStage.setMinWidth(dimensions.getWidth());
mainStage.setMinHeight(dimensions.getHeight());
mainStage.setMaxWidth(dimensions.getWidth());
mainStage.setMaxHeight(dimensions.getHeight());
mainStage.setX(0);
mainStage.setY(0);
}
public void minimizeWindow() {
if (isTestMode()) {
triggerEvent(new WindowResizeEvent(WindowResizeEvent.EventType.MINIMIZE_WINDOW));
}
mainStage.setIconified(true);
menuBar.scrollTo(columns.getCurrentlySelectedColumn().get(), columns.getChildren().size());
}
public HWND getMainWindowHandle() {
return mainWindowHandle;
}
}
| disables UI components while logging in for UI
| src/main/java/ui/UI.java | disables UI components while logging in for UI |
|
Java | apache-2.0 | 67dc3a3477943d79778047c846fd3f3e421b2497 | 0 | photon-infotech/commons,photon-infotech/commons | package com.photon.phresco.impl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import javax.xml.bind.JAXBException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.opensymphony.xwork2.util.ArrayUtils;
import com.photon.phresco.api.ApplicationProcessor;
import com.photon.phresco.commons.model.ApplicationInfo;
import com.photon.phresco.commons.model.ArtifactGroup;
import com.photon.phresco.configuration.Configuration;
import com.photon.phresco.exception.PhrescoException;
import com.photon.phresco.plugins.model.Assembly.FileSets.FileSet;
import com.photon.phresco.plugins.model.Assembly.FileSets.FileSet.Includes;
import com.photon.phresco.plugins.model.Mojos.Mojo.Configuration.Parameters.Parameter;
import com.photon.phresco.plugins.util.MojoProcessor;
import com.photon.phresco.plugins.util.WarConfigProcessor;
import com.photon.phresco.util.Constants;
import com.photon.phresco.util.ProjectUtils;
import com.photon.phresco.util.Utility;
import com.phresco.pom.exception.PhrescoPomException;
import com.phresco.pom.util.PomProcessor;
public class HtmlApplicationProcessor implements ApplicationProcessor {
@Override
public void preCreate(ApplicationInfo appInfo) throws PhrescoException {
// TODO Auto-generated method stub
}
@Override
public void preUpdate(ApplicationInfo appInfo) throws PhrescoException {
// TODO Auto-generated method stub
}
@Override
public void postCreate(ApplicationInfo appInfo) throws PhrescoException {
// TODO Auto-generated method stub
}
@Override
public void postUpdate(ApplicationInfo appInfo, List<ArtifactGroup> artifactGroups, List<ArtifactGroup> deletedFeatures) throws PhrescoException {
File pomFile = new File(Utility.getProjectHome() + appInfo.getAppDirName() + File.separator
+ Constants.POM_NAME);
ProjectUtils projectUtils = new ProjectUtils();
projectUtils.deletePluginExecutionFromPom(pomFile);
if (CollectionUtils.isNotEmpty(artifactGroups)) {
BufferedReader breader = null;
try {
projectUtils.updatePOMWithPluginArtifact(pomFile, artifactGroups);
projectUtils.deletePluginFromPom(pomFile);
projectUtils.addServerPlugin(appInfo, pomFile);
breader = projectUtils.ExtractFeature(appInfo);
String line = "";
while ((line = breader.readLine()) != null) {
if (line.startsWith("[INFO] BUILD SUCCESS")) {
readConfigJson(appInfo);
}
}
} catch (IOException e) {
throw new PhrescoException(e);
} finally {
try {
if (breader != null) {
breader.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
}
@Override
public List<Configuration> preConfiguration(ApplicationInfo appInfo, String componentName, String envName) throws PhrescoException {
StringBuilder sb = new StringBuilder(Utility.getProjectHome())
.append(appInfo.getAppDirName())
.append(File.separator)
.append("src")
.append(File.separator)
.append("main")
.append(File.separator)
.append("webapp")
.append(File.separator)
.append("json")
.append(File.separator)
.append(Constants.CONFIG_JSON);
File jsonFile = new File(sb.toString());
if(!jsonFile.exists()) {
return null;
}
return getConfiguration(jsonFile, envName, componentName);
}
@Override
public void postConfiguration(ApplicationInfo appInfo, List<Configuration> configurations)
throws PhrescoException {
Configuration configuration = configurations.get(0);
JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
List<JsonElement> jsonElements = new ArrayList<JsonElement>();
String envName = configuration.getEnvName();
String configType = configuration.getType().toLowerCase();
String configName = "";
if(configuration.getType().equalsIgnoreCase("components")) {
configName = configuration.getProperties().getProperty("featureName");
} else {
configName = configuration.getName();
}
String json = gson.toJson(configuration.getProperties());
JsonElement propertyJsonElement = parser.parse(json);
JsonObject propJsonObject = new JsonObject();
propJsonObject.add(configName, propertyJsonElement);
JsonObject typeJsonObject = new JsonObject();
typeJsonObject.add(configType, propJsonObject);
jsonElements.add(propJsonObject);
writeJson(appInfo, jsonElements, envName, configType);
}
@Override
public List<Configuration> preFeatureConfiguration(ApplicationInfo appInfo,
String componentName) throws PhrescoException {
try {
StringBuilder sb = new StringBuilder(Utility.getProjectHome())
.append(appInfo.getAppDirName())
.append(getFeaturePath(appInfo))
.append(File.separator)
.append(componentName)
.append(File.separator)
.append("config")
.append(File.separator)
.append(Constants.CONFIG_JSON);
File jsonFile = new File(sb.toString());
if(!jsonFile.exists()) {
return null;
}
return getConfiguration(jsonFile, componentName);
} catch (Exception e) {
throw new PhrescoException(e);
}
}
private List<Configuration> getConfiguration(File jsonFile, String componentName) throws PhrescoException {
FileReader reader = null;
try {
reader = new FileReader(jsonFile);
JsonParser parser = new JsonParser();
Object obj = parser.parse(reader);
JsonObject jsonObject = (JsonObject) obj;
List<Configuration> configurations = new ArrayList<Configuration>();
Configuration configuration = new Configuration();
Properties properties = new Properties();
Set<Entry<String,JsonElement>> entrySet = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : entrySet) {
JsonElement value = entry.getValue();
JsonObject asJsonObject = value.getAsJsonObject();
Set<Entry<String,JsonElement>> entrySet2 = asJsonObject.entrySet();
for (Entry<String, JsonElement> entry2 : entrySet2) {
JsonElement value2 = entry2.getValue();
JsonObject asJsonObject1 = value2.getAsJsonObject();
Set<Entry<String,JsonElement>> entrySet3 = asJsonObject1.entrySet();
for (Entry<String, JsonElement> entry3 : entrySet3) {
String key = entry3.getKey();
JsonElement value3 = entry3.getValue();
properties.setProperty(key, value3.getAsString());
}
}
configuration.setProperties(properties);
configurations.add(configuration);
return configurations;
}
} catch (Exception e) {
throw new PhrescoException(e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
return null;
}
private List<Configuration> getConfiguration(File jsonFile, String envName, String componentName) throws PhrescoException {
FileReader reader = null;
try {
reader = new FileReader(jsonFile);
JsonParser parser = new JsonParser();
Object obj = parser.parse(reader);
JsonObject jsonObject = (JsonObject) obj;
List<Configuration> configurations = new ArrayList<Configuration>();
Configuration configuration = new Configuration();
Properties properties = new Properties();
Set<Entry<String,JsonElement>> entrySet = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : entrySet) {
JsonElement value = entry.getValue();
JsonArray jsonArray = value.getAsJsonArray();
for (JsonElement jsonElement : jsonArray) {
JsonObject asJsonObject = jsonElement.getAsJsonObject();
JsonElement name = asJsonObject.get(Constants.NAME);
if (name.getAsString().equals(envName)) {
JsonElement components = asJsonObject.get(Constants.COMPONENTS);
JsonObject asJsonObj = components.getAsJsonObject();
Set<Entry<String, JsonElement>> parentEntrySet = asJsonObj.entrySet();
for (Entry<String, JsonElement> entry1 : parentEntrySet) {
String key = entry1.getKey();
if (key.equalsIgnoreCase(componentName)) {
JsonObject valueJsonObj = entry1.getValue().getAsJsonObject();
Set<Entry<String,JsonElement>> valueEntrySet = valueJsonObj.entrySet();
for (Entry<String, JsonElement> valueEntry : valueEntrySet) {
String key1 = valueEntry.getKey();
JsonElement value1 = valueEntry.getValue();
properties.setProperty(key1, value1.getAsString());
}
}
}
configuration.setProperties(properties);
configurations.add(configuration);
return configurations;
}
}
}
} catch (Exception e) {
throw new PhrescoException(e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
return null;
}
private void readConfigJson(ApplicationInfo appInfo) throws PhrescoException {
FileReader reader = null;
try {
File componentDir = new File(Utility.getProjectHome() + appInfo.getAppDirName() + File.separator + getFeaturePath(appInfo) + File.separator);
File[] listFiles = componentDir.listFiles();
if(ArrayUtils.isEmpty(listFiles)) {
return;
}
List<JsonElement> jsonElements = new ArrayList<JsonElement>();
if(listFiles.length > 0) {
for (File file : listFiles) {
String jsonFile = file.getPath() + File.separator + "config" + File.separator + Constants.CONFIG_JSON;
if (new File(jsonFile).exists()) {
reader = new FileReader(jsonFile);
JsonParser parser = new JsonParser();
Object obj = parser.parse(reader);
JsonObject jsonObject = (JsonObject) obj;
JsonElement jsonElement = jsonObject.get(Constants.COMPONENTS);
jsonElements.add(jsonElement);
}
}
writeJson(appInfo, jsonElements, "Production", Constants.COMPONENTS);
}
} catch (IOException e) {
throw new PhrescoException(e);
} catch (PhrescoException e) {
throw new PhrescoException(e);
}
}
private void writeJson(ApplicationInfo appInfo, List<JsonElement> compJsonElements, String environment, String type) throws PhrescoException {
File jsonDir = new File(Utility.getProjectHome() +
appInfo.getAppDirName() + File.separator + "src/main/webapp/json");
if (!jsonDir.exists()) {
return;
}
File configFile = new File(getAppLevelConfigJson(appInfo.getAppDirName()));
JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonObject jsonObject = new JsonObject();
JsonObject envObject = new JsonObject();
if (!configFile.exists()) {
jsonObject.addProperty(Constants.NAME, environment);
StringBuilder sb = new StringBuilder();
sb.append("{");
for (JsonElement jsonElement : compJsonElements) {
String jsonString = jsonElement.toString();
sb.append(jsonString.substring(1, jsonString.length() - 1));
sb.append(",");
}
String compConfig = sb.toString();
compConfig = compConfig.substring(0, compConfig.length() - 1) + "}";
jsonObject.add(type, parser.parse(compConfig));
envObject.add(Constants.ENVIRONMENTS, parser.parse(Collections.singletonList(jsonObject).toString()));
} else {
FileReader reader = null;
try {
reader = new FileReader(configFile);
Object obj = parser.parse(reader);
envObject = (JsonObject) obj;
JsonArray environments = (JsonArray) envObject.get(Constants.ENVIRONMENTS);
jsonObject = getProductionEnv(environments, environment);
JsonElement components = null;
for (JsonElement compJsonElement : compJsonElements) {
JsonObject allComponents = null;
if(jsonObject == null) {
jsonObject = new JsonObject();
JsonElement jsonElement = envObject.get(Constants.ENVIRONMENTS);
String oldObj = jsonElement.toString().substring(1, jsonElement.toString().length()-1).concat(",");
jsonObject.addProperty(Constants.NAME, environment);
jsonObject.add(type, compJsonElement);
String newObj = jsonObject.toString();
envObject.add(Constants.ENVIRONMENTS, parser.parse(Collections.singletonList(oldObj + newObj).toString()));
} else {
components = jsonObject.get(type);
}
if (components == null) {
jsonObject.add(type, compJsonElement);
} else {
allComponents = components.getAsJsonObject();
Set<Entry<String,JsonElement>> entrySet = compJsonElement.getAsJsonObject().entrySet();
Entry<String, JsonElement> entry = entrySet.iterator().next();
String key = entry.getKey();
// if (allComponents.get(key) == null) {
allComponents.add(key, entry.getValue());
// }
}
}
} catch (FileNotFoundException e) {
throw new PhrescoException(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
}
FileWriter writer = null;
String json = gson.toJson(envObject);
try {
writer = new FileWriter(configFile);
writer.write(json);
writer.flush();
} catch (IOException e) {
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
private JsonObject getProductionEnv(JsonArray environments, String environment) {
for (JsonElement jsonElement : environments) {
JsonElement envName = ((JsonObject)jsonElement).get(Constants.NAME);
if (environment.equals(envName.getAsString())) {
return (JsonObject) jsonElement;
}
}
return null;
}
@Override
public void postFeatureConfiguration(ApplicationInfo appInfo, List<Configuration> configs, String featureName)
throws PhrescoException {
FileWriter writer = null;
StringBuilder sb = new StringBuilder(Utility.getProjectHome())
.append(appInfo.getAppDirName())
.append(getFeaturePath(appInfo))
.append(File.separator)
.append(featureName)
.append(File.separator)
.append("config");
if (new File(sb.toString()).exists()) {
try {
Gson gson = new Gson();
String jsonFile = sb.toString() + File.separator + Constants.CONFIG_JSON;
String json = gson.toJson(configs.get(0).getProperties());
JsonParser parser = new JsonParser();
JsonElement propertyJsonElement = parser.parse(json);
JsonObject propJsonObject = new JsonObject();
propJsonObject.add(featureName, propertyJsonElement);
JsonObject jsonObject = new JsonObject();
jsonObject.add(Constants.COMPONENTS, propJsonObject);
writer = new FileWriter(jsonFile);
json = gson.toJson(jsonObject);
writer.write(json);
writer.flush();
} catch (IOException e) {
throw new PhrescoException(e);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
}
private String getFeaturePath(ApplicationInfo appInfo) throws PhrescoException {
String pomPath = Utility.getProjectHome() + appInfo.getAppDirName() + File.separator + Constants.POM_NAME;
try {
PomProcessor processor = new PomProcessor(new File(pomPath));
return processor.getProperty(Constants.POM_PROP_KEY_COMPONENTS_SOURCE_DIR);
} catch (PhrescoPomException e) {
throw new PhrescoException(e);
}
}
@Override
public void preBuild(ApplicationInfo appInfo) throws PhrescoException {
FileReader reader = null;
FileWriter writer = null;
try {
String baseDir = Utility.getProjectHome() + appInfo.getAppDirName();
File pluginInfoFile = new File(baseDir + File.separator + Constants.PACKAGE_INFO_FILE);
MojoProcessor mojoProcessor = new MojoProcessor(pluginInfoFile);
Parameter defaultThemeParameter = mojoProcessor.getParameter(Constants.MVN_GOAL_PACKAGE, Constants.MOJO_KEY_DEFAULT_THEME);
String appLevelConfigJson = getAppLevelConfigJson(appInfo.getAppDirName());
if (defaultThemeParameter != null && new File(appLevelConfigJson).exists()) {
reader = new FileReader(appLevelConfigJson);
JsonParser parser = new JsonParser();
Object obj = parser.parse(reader);
JsonObject jsonObject = (JsonObject) obj;
jsonObject.addProperty(Constants.MOJO_KEY_DEFAULT_THEME, defaultThemeParameter.getValue());
Gson gson = new Gson();
String json = gson.toJson(jsonObject);
writer = new FileWriter(appLevelConfigJson);
writer.write(json);
}
Parameter themesParameter = mojoProcessor.getParameter(Constants.MVN_GOAL_PACKAGE, Constants.MOJO_KEY_THEMES);
if (themesParameter != null) {
StringBuilder warConfigFilePath = new StringBuilder(baseDir)
.append(File.separator)
.append(".phresco")
.append(File.separator)
.append("war-config.xml");
File warConfigFile = new File(warConfigFilePath.toString());
WarConfigProcessor warConfigProcessor = new WarConfigProcessor(warConfigFile);
List<String> includes = new ArrayList<String>();
String value = themesParameter.getValue();
if (StringUtils.isNotEmpty(value)) {
includes.addAll(Arrays.asList(value.split(",")));
}
setFileSetIncludes(warConfigProcessor, "themesIncludeFile", includes);
}
} catch (PhrescoException e) {
throw new PhrescoException(e);
} catch (JAXBException e) {
throw new PhrescoException(e);
} catch (IOException e) {
throw new PhrescoException(e);
} finally {
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
private String getAppLevelConfigJson(String appDirName) {
StringBuilder sb = new StringBuilder(Utility.getProjectHome())
.append(appDirName)
.append(File.separator)
.append("src")
.append(File.separator)
.append("main")
.append(File.separator)
.append("webapp")
.append(File.separator)
.append("json")
.append(File.separator)
.append(Constants.CONFIG_JSON);
return sb.toString();
}
private void setFileSetIncludes(WarConfigProcessor warConfigProcessor, String fileSetId, List<String> toBeIncluded) throws PhrescoException {
try {
FileSet fileSet = warConfigProcessor.getFileSet(fileSetId);
if (fileSet == null) {
fileSet = new FileSet();
fileSet.setDirectory("src/main/webapp/themes");
fileSet.setOutputDirectory("src/main/webapp/themes");
fileSet.setId(fileSetId);
}
if (fileSet.getIncludes() == null) {
Includes includes = new Includes();
fileSet.setIncludes(includes);
}
if (CollectionUtils.isNotEmpty(toBeIncluded)) {
fileSet.getIncludes().getInclude().clear();
for (String include : toBeIncluded) {
fileSet.getIncludes().getInclude().add(include);
}
}
warConfigProcessor.createFileSet(fileSet);
warConfigProcessor.save();
} catch (JAXBException e) {
throw new PhrescoException();
}
}
@Override
public void postBuild(ApplicationInfo appInfo) throws PhrescoException {
// TODO Auto-generated method stub
}
} | src/main/java/com/photon/phresco/impl/HtmlApplicationProcessor.java | package com.photon.phresco.impl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import javax.xml.bind.JAXBException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.opensymphony.xwork2.util.ArrayUtils;
import com.photon.phresco.api.ApplicationProcessor;
import com.photon.phresco.commons.model.ApplicationInfo;
import com.photon.phresco.commons.model.ArtifactGroup;
import com.photon.phresco.configuration.Configuration;
import com.photon.phresco.exception.PhrescoException;
import com.photon.phresco.plugins.model.Assembly.FileSets.FileSet;
import com.photon.phresco.plugins.model.Assembly.FileSets.FileSet.Includes;
import com.photon.phresco.plugins.model.Mojos.Mojo.Configuration.Parameters.Parameter;
import com.photon.phresco.plugins.util.MojoProcessor;
import com.photon.phresco.plugins.util.WarConfigProcessor;
import com.photon.phresco.util.Constants;
import com.photon.phresco.util.ProjectUtils;
import com.photon.phresco.util.Utility;
import com.phresco.pom.exception.PhrescoPomException;
import com.phresco.pom.util.PomProcessor;
public class HtmlApplicationProcessor implements ApplicationProcessor {
@Override
public void preCreate(ApplicationInfo appInfo) throws PhrescoException {
// TODO Auto-generated method stub
}
@Override
public void preUpdate(ApplicationInfo appInfo) throws PhrescoException {
// TODO Auto-generated method stub
}
@Override
public void postCreate(ApplicationInfo appInfo) throws PhrescoException {
// TODO Auto-generated method stub
}
@Override
public void postUpdate(ApplicationInfo appInfo, List<ArtifactGroup> artifactGroups, List<ArtifactGroup> deletedFeatures) throws PhrescoException {
File pomFile = new File(Utility.getProjectHome() + appInfo.getAppDirName() + File.separator
+ Constants.POM_NAME);
ProjectUtils projectUtils = new ProjectUtils();
projectUtils.deletePluginExecutionFromPom(pomFile);
if (CollectionUtils.isNotEmpty(artifactGroups)) {
BufferedReader breader = null;
try {
projectUtils.updatePOMWithPluginArtifact(pomFile, artifactGroups);
projectUtils.deletePluginFromPom(pomFile);
projectUtils.addServerPlugin(appInfo, pomFile);
breader = projectUtils.ExtractFeature(appInfo);
String line = "";
while ((line = breader.readLine()) != null) {
if (line.startsWith("[INFO] BUILD SUCCESS")) {
readConfigJson(appInfo);
}
}
} catch (IOException e) {
throw new PhrescoException(e);
} finally {
try {
if (breader != null) {
breader.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
}
@Override
public List<Configuration> preConfiguration(ApplicationInfo appInfo, String componentName, String envName) throws PhrescoException {
StringBuilder sb = new StringBuilder(Utility.getProjectHome())
.append(appInfo.getAppDirName())
.append(File.separator)
.append("src")
.append(File.separator)
.append("main")
.append(File.separator)
.append("webapp")
.append(File.separator)
.append("json")
.append(File.separator)
.append(Constants.CONFIG_JSON);
File jsonFile = new File(sb.toString());
if(!jsonFile.exists()) {
return null;
}
return getConfiguration(jsonFile, envName, componentName);
}
@Override
public void postConfiguration(ApplicationInfo appInfo, List<Configuration> configurations)
throws PhrescoException {
Configuration configuration = configurations.get(0);
JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
List<JsonElement> jsonElements = new ArrayList<JsonElement>();
String envName = configuration.getEnvName();
String configType = configuration.getType().toLowerCase();
String configName = "";
if(configuration.getType().equalsIgnoreCase("components")) {
configName = configuration.getProperties().getProperty("featureName");
} else {
configName = configuration.getName();
}
String json = gson.toJson(configuration.getProperties());
JsonElement propertyJsonElement = parser.parse(json);
JsonObject propJsonObject = new JsonObject();
propJsonObject.add(configName, propertyJsonElement);
JsonObject typeJsonObject = new JsonObject();
typeJsonObject.add(configType, propJsonObject);
jsonElements.add(propJsonObject);
writeJson(appInfo, jsonElements, envName, configType);
}
@Override
public List<Configuration> preFeatureConfiguration(ApplicationInfo appInfo,
String componentName) throws PhrescoException {
try {
StringBuilder sb = new StringBuilder(Utility.getProjectHome())
.append(appInfo.getAppDirName())
.append(getFeaturePath(appInfo))
.append(File.separator)
.append(componentName)
.append(File.separator)
.append("config")
.append(File.separator)
.append(Constants.CONFIG_JSON);
File jsonFile = new File(sb.toString());
if(!jsonFile.exists()) {
return null;
}
return getConfiguration(jsonFile, componentName);
} catch (Exception e) {
throw new PhrescoException(e);
}
}
private List<Configuration> getConfiguration(File jsonFile, String componentName) throws PhrescoException {
FileReader reader = null;
try {
reader = new FileReader(jsonFile);
JsonParser parser = new JsonParser();
Object obj = parser.parse(reader);
JsonObject jsonObject = (JsonObject) obj;
List<Configuration> configurations = new ArrayList<Configuration>();
Configuration configuration = new Configuration();
Properties properties = new Properties();
Set<Entry<String,JsonElement>> entrySet = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : entrySet) {
JsonElement value = entry.getValue();
JsonObject asJsonObject = value.getAsJsonObject();
Set<Entry<String,JsonElement>> entrySet2 = asJsonObject.entrySet();
for (Entry<String, JsonElement> entry2 : entrySet2) {
JsonElement value2 = entry2.getValue();
JsonObject asJsonObject1 = value2.getAsJsonObject();
Set<Entry<String,JsonElement>> entrySet3 = asJsonObject1.entrySet();
for (Entry<String, JsonElement> entry3 : entrySet3) {
String key = entry3.getKey();
JsonElement value3 = entry3.getValue();
properties.setProperty(key, value3.getAsString());
}
}
configuration.setProperties(properties);
configurations.add(configuration);
return configurations;
}
} catch (Exception e) {
throw new PhrescoException(e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
return null;
}
private List<Configuration> getConfiguration(File jsonFile, String envName, String componentName) throws PhrescoException {
FileReader reader = null;
try {
reader = new FileReader(jsonFile);
JsonParser parser = new JsonParser();
Object obj = parser.parse(reader);
JsonObject jsonObject = (JsonObject) obj;
List<Configuration> configurations = new ArrayList<Configuration>();
Configuration configuration = new Configuration();
Properties properties = new Properties();
Set<Entry<String,JsonElement>> entrySet = jsonObject.entrySet();
for (Entry<String, JsonElement> entry : entrySet) {
JsonElement value = entry.getValue();
JsonArray jsonArray = value.getAsJsonArray();
for (JsonElement jsonElement : jsonArray) {
JsonObject asJsonObject = jsonElement.getAsJsonObject();
JsonElement name = asJsonObject.get(Constants.NAME);
if (name.getAsString().equals(envName)) {
JsonElement components = asJsonObject.get(Constants.COMPONENTS);
JsonObject asJsonObj = components.getAsJsonObject();
Set<Entry<String, JsonElement>> parentEntrySet = asJsonObj.entrySet();
for (Entry<String, JsonElement> entry1 : parentEntrySet) {
String key = entry1.getKey();
if (key.equalsIgnoreCase(componentName)) {
JsonObject valueJsonObj = entry1.getValue().getAsJsonObject();
Set<Entry<String,JsonElement>> valueEntrySet = valueJsonObj.entrySet();
for (Entry<String, JsonElement> valueEntry : valueEntrySet) {
String key1 = valueEntry.getKey();
JsonElement value1 = valueEntry.getValue();
properties.setProperty(key1, value1.getAsString());
}
}
}
configuration.setProperties(properties);
configurations.add(configuration);
return configurations;
}
}
}
} catch (Exception e) {
throw new PhrescoException(e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
return null;
}
private void readConfigJson(ApplicationInfo appInfo) throws PhrescoException {
FileReader reader = null;
try {
File componentDir = new File(Utility.getProjectHome() + appInfo.getAppDirName() + File.separator + getFeaturePath(appInfo) + File.separator);
File[] listFiles = componentDir.listFiles();
if(ArrayUtils.isEmpty(listFiles)) {
return;
}
List<JsonElement> jsonElements = new ArrayList<JsonElement>();
if(listFiles.length > 0) {
for (File file : listFiles) {
String jsonFile = file.getPath() + File.separator + "config" + File.separator + Constants.CONFIG_JSON;
if (new File(jsonFile).exists()) {
reader = new FileReader(jsonFile);
JsonParser parser = new JsonParser();
Object obj = parser.parse(reader);
JsonObject jsonObject = (JsonObject) obj;
JsonElement jsonElement = jsonObject.get(Constants.COMPONENTS);
jsonElements.add(jsonElement);
}
}
writeJson(appInfo, jsonElements, "Production", Constants.COMPONENTS);
}
} catch (IOException e) {
throw new PhrescoException(e);
} catch (PhrescoException e) {
throw new PhrescoException(e);
}
}
private void writeJson(ApplicationInfo appInfo, List<JsonElement> compJsonElements, String environment, String type) throws PhrescoException {
File jsonDir = new File(Utility.getProjectHome() +
appInfo.getAppDirName() + File.separator + "src/main/webapp/json");
if (!jsonDir.exists()) {
return;
}
File configFile = new File(getAppLevelConfigJson(appInfo.getAppDirName()));
JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonObject jsonObject = new JsonObject();
JsonObject envObject = new JsonObject();
if (!configFile.exists()) {
jsonObject.addProperty(Constants.NAME, environment);
StringBuilder sb = new StringBuilder();
sb.append("{");
for (JsonElement jsonElement : compJsonElements) {
String jsonString = jsonElement.toString();
sb.append(jsonString.substring(1, jsonString.length() - 1));
sb.append(",");
}
String compConfig = sb.toString();
compConfig = compConfig.substring(0, compConfig.length() - 1) + "}";
jsonObject.add(type, parser.parse(compConfig));
envObject.add(Constants.ENVIRONMENTS, parser.parse(Collections.singletonList(jsonObject).toString()));
} else {
FileReader reader = null;
try {
reader = new FileReader(configFile);
Object obj = parser.parse(reader);
envObject = (JsonObject) obj;
JsonArray environments = (JsonArray) envObject.get(Constants.ENVIRONMENTS);
jsonObject = getProductionEnv(environments, environment);
JsonElement components = null;
for (JsonElement compJsonElement : compJsonElements) {
JsonObject allComponents = null;
if(jsonObject == null) {
jsonObject = new JsonObject();
JsonElement jsonElement = envObject.get(Constants.ENVIRONMENTS);
String oldObj = jsonElement.toString().substring(1, jsonElement.toString().length()-1).concat(",");
jsonObject.addProperty(Constants.NAME, environment);
jsonObject.add(type, compJsonElement);
String newObj = jsonObject.toString();
envObject.add(Constants.ENVIRONMENTS, parser.parse(Collections.singletonList(oldObj + newObj).toString()));
} else {
components = jsonObject.get(type);
}
if (components == null) {
jsonObject.add(type, compJsonElement);
} else {
allComponents = components.getAsJsonObject();
Set<Entry<String,JsonElement>> entrySet = compJsonElement.getAsJsonObject().entrySet();
Entry<String, JsonElement> entry = entrySet.iterator().next();
String key = entry.getKey();
// if (allComponents.get(key) == null) {
allComponents.add(key, entry.getValue());
// }
}
}
} catch (FileNotFoundException e) {
throw new PhrescoException(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
}
FileWriter writer = null;
String json = gson.toJson(envObject);
try {
writer = new FileWriter(configFile);
writer.write(json);
writer.flush();
} catch (IOException e) {
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
private JsonObject getProductionEnv(JsonArray environments, String environment) {
for (JsonElement jsonElement : environments) {
JsonElement envName = ((JsonObject)jsonElement).get(Constants.NAME);
if (environment.equals(envName.getAsString())) {
return (JsonObject) jsonElement;
}
}
return null;
}
@Override
public void postFeatureConfiguration(ApplicationInfo appInfo, List<Configuration> configs, String featureName)
throws PhrescoException {
FileWriter writer = null;
StringBuilder sb = new StringBuilder(Utility.getProjectHome())
.append(appInfo.getAppDirName())
.append(getFeaturePath(appInfo))
.append(File.separator)
.append(featureName)
.append(File.separator)
.append("config");
if (new File(sb.toString()).exists()) {
try {
Gson gson = new Gson();
String jsonFile = sb.toString() + File.separator + Constants.CONFIG_JSON;
String json = gson.toJson(configs.get(0).getProperties());
JsonParser parser = new JsonParser();
JsonElement propertyJsonElement = parser.parse(json);
JsonObject propJsonObject = new JsonObject();
propJsonObject.add(featureName, propertyJsonElement);
JsonObject jsonObject = new JsonObject();
jsonObject.add(Constants.COMPONENTS, propJsonObject);
writer = new FileWriter(jsonFile);
json = gson.toJson(jsonObject);
writer.write(json);
writer.flush();
} catch (IOException e) {
throw new PhrescoException(e);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
}
private String getFeaturePath(ApplicationInfo appInfo) throws PhrescoException {
String pomPath = Utility.getProjectHome() + appInfo.getAppDirName() + File.separator + Constants.POM_NAME;
try {
PomProcessor processor = new PomProcessor(new File(pomPath));
return processor.getProperty(Constants.POM_PROP_KEY_COMPONENTS_SOURCE_DIR);
} catch (PhrescoPomException e) {
throw new PhrescoException(e);
}
}
@Override
public void preBuild(ApplicationInfo appInfo) throws PhrescoException {
FileReader reader = null;
FileWriter writer = null;
try {
String baseDir = Utility.getProjectHome() + appInfo.getAppDirName();
File pluginInfoFile = new File(baseDir + File.separator + Constants.PACKAGE_INFO_FILE);
MojoProcessor mojoProcessor = new MojoProcessor(pluginInfoFile);
Parameter defaultThemeParameter = mojoProcessor.getParameter(Constants.MVN_GOAL_PACKAGE, Constants.MOJO_KEY_DEFAULT_THEME);
String appLevelConfigJson = getAppLevelConfigJson(appInfo.getAppDirName());
if (new File(appLevelConfigJson).exists()) {
reader = new FileReader(appLevelConfigJson);
JsonParser parser = new JsonParser();
Object obj = parser.parse(reader);
JsonObject jsonObject = (JsonObject) obj;
jsonObject.addProperty(Constants.MOJO_KEY_DEFAULT_THEME, defaultThemeParameter.getValue());
Gson gson = new Gson();
String json = gson.toJson(jsonObject);
writer = new FileWriter(appLevelConfigJson);
writer.write(json);
}
Parameter themesParameter = mojoProcessor.getParameter(Constants.MVN_GOAL_PACKAGE, Constants.MOJO_KEY_THEMES);
if (themesParameter != null) {
StringBuilder warConfigFilePath = new StringBuilder(baseDir)
.append(File.separator)
.append(".phresco")
.append(File.separator)
.append("war-config.xml");
File warConfigFile = new File(warConfigFilePath.toString());
WarConfigProcessor warConfigProcessor = new WarConfigProcessor(warConfigFile);
List<String> includes = new ArrayList<String>();
String value = themesParameter.getValue();
if (StringUtils.isNotEmpty(value)) {
includes.addAll(Arrays.asList(value.split(",")));
}
setFileSetIncludes(warConfigProcessor, "themesIncludeFile", includes);
}
} catch (PhrescoException e) {
throw new PhrescoException(e);
} catch (JAXBException e) {
throw new PhrescoException(e);
} catch (IOException e) {
throw new PhrescoException(e);
} finally {
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
throw new PhrescoException(e);
}
}
}
private String getAppLevelConfigJson(String appDirName) {
StringBuilder sb = new StringBuilder(Utility.getProjectHome())
.append(appDirName)
.append(File.separator)
.append("src")
.append(File.separator)
.append("main")
.append(File.separator)
.append("webapp")
.append(File.separator)
.append("json")
.append(File.separator)
.append(Constants.CONFIG_JSON);
return sb.toString();
}
private void setFileSetIncludes(WarConfigProcessor warConfigProcessor, String fileSetId, List<String> toBeIncluded) throws PhrescoException {
try {
FileSet fileSet = warConfigProcessor.getFileSet(fileSetId);
if (fileSet == null) {
fileSet = new FileSet();
fileSet.setDirectory("src/main/webapp/themes");
fileSet.setOutputDirectory("src/main/webapp/themes");
fileSet.setId(fileSetId);
}
if (fileSet.getIncludes() == null) {
Includes includes = new Includes();
fileSet.setIncludes(includes);
}
if (CollectionUtils.isNotEmpty(toBeIncluded)) {
fileSet.getIncludes().getInclude().clear();
for (String include : toBeIncluded) {
fileSet.getIncludes().getInclude().add(include);
}
}
warConfigProcessor.createFileSet(fileSet);
warConfigProcessor.save();
} catch (JAXBException e) {
throw new PhrescoException();
}
}
@Override
public void postBuild(ApplicationInfo appInfo) throws PhrescoException {
// TODO Auto-generated method stub
}
} | null checked
| src/main/java/com/photon/phresco/impl/HtmlApplicationProcessor.java | null checked |
|
Java | apache-2.0 | 7a513a9de1b145f1aad66f9c83587c4b6c3eba3c | 0 | thc202/zaproxy,thc202/zaproxy,meitar/zaproxy,lightsey/zaproxy,mustafa421/zaproxy,gsavastano/zaproxy,Harinus/zaproxy,meitar/zaproxy,psiinon/zaproxy,Harinus/zaproxy,meitar/zaproxy,zaproxy/zaproxy,rajiv65/zaproxy,psiinon/zaproxy,zapbot/zaproxy,lightsey/zaproxy,kingthorin/zaproxy,meitar/zaproxy,thc202/zaproxy,zapbot/zaproxy,zapbot/zaproxy,JordanGS/zaproxy,gmaran23/zaproxy,lightsey/zaproxy,gmaran23/zaproxy,UjuE/zaproxy,mustafa421/zaproxy,gmaran23/zaproxy,zapbot/zaproxy,Ali-Razmjoo/zaproxy,meitar/zaproxy,kingthorin/zaproxy,zaproxy/zaproxy,psiinon/zaproxy,Ali-Razmjoo/zaproxy,NVolcz/zaproxy,lightsey/zaproxy,zaproxy/zaproxy,Harinus/zaproxy,NVolcz/zaproxy,JordanGS/zaproxy,thc202/zaproxy,zapbot/zaproxy,lightsey/zaproxy,Harinus/zaproxy,rajiv65/zaproxy,zaproxy/zaproxy,Harinus/zaproxy,Harinus/zaproxy,meitar/zaproxy,Harinus/zaproxy,JordanGS/zaproxy,mustafa421/zaproxy,kingthorin/zaproxy,NVolcz/zaproxy,NVolcz/zaproxy,kingthorin/zaproxy,zapbot/zaproxy,rajiv65/zaproxy,Ali-Razmjoo/zaproxy,gsavastano/zaproxy,rajiv65/zaproxy,UjuE/zaproxy,psiinon/zaproxy,NVolcz/zaproxy,gmaran23/zaproxy,rajiv65/zaproxy,rajiv65/zaproxy,zapbot/zaproxy,UjuE/zaproxy,lightsey/zaproxy,gsavastano/zaproxy,UjuE/zaproxy,gmaran23/zaproxy,UjuE/zaproxy,meitar/zaproxy,gsavastano/zaproxy,lightsey/zaproxy,thc202/zaproxy,JordanGS/zaproxy,mustafa421/zaproxy,Ali-Razmjoo/zaproxy,UjuE/zaproxy,gsavastano/zaproxy,mustafa421/zaproxy,mustafa421/zaproxy,JordanGS/zaproxy,kingthorin/zaproxy,mustafa421/zaproxy,psiinon/zaproxy,zaproxy/zaproxy,zaproxy/zaproxy,NVolcz/zaproxy,psiinon/zaproxy,thc202/zaproxy,JordanGS/zaproxy,gmaran23/zaproxy,psiinon/zaproxy,gmaran23/zaproxy,kingthorin/zaproxy,Ali-Razmjoo/zaproxy,meitar/zaproxy,Ali-Razmjoo/zaproxy,rajiv65/zaproxy,Ali-Razmjoo/zaproxy,JordanGS/zaproxy,thc202/zaproxy,UjuE/zaproxy,zaproxy/zaproxy,gsavastano/zaproxy,NVolcz/zaproxy,gsavastano/zaproxy,kingthorin/zaproxy | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.httpsessions;
import java.net.HttpCookie;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.httpclient.Cookie;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.session.CookieBasedSessionManagementHelper;
/**
* The Class SiteHttpSessions stores all the information regarding the sessions for a particular
* Site.
*/
public class HttpSessionsSite {
/** The Constant log. */
private static final Logger log = Logger.getLogger(HttpSessionsSite.class);
/** The last session id. */
private static int lastGeneratedSessionID = 0;
/** The extension. */
private ExtensionHttpSessions extension;
/** The site. */
private String site;
/** The sessions as a LinkedHashSet. */
private Set<HttpSession> sessions;
/** The active session. */
private HttpSession activeSession;
/** The model associated with this site. */
private HttpSessionsTableModel model;
/**
* Instantiates a new site http sessions object.
*
* @param extension the extension
* @param site the site
*/
public HttpSessionsSite(ExtensionHttpSessions extension, String site) {
super();
this.extension = extension;
this.site = site;
this.sessions = new LinkedHashSet<>();
this.model = new HttpSessionsTableModel(this);
this.activeSession = null;
}
/**
* Adds a new http session to this site.
*
* @param session the session
*/
public void addHttpSession(HttpSession session) {
synchronized (this.sessions) {
this.sessions.add(session);
}
this.model.addHttpSession(session);
}
/**
* Removes an existing session.
*
* @param session the session
*/
public void removeHttpSession(HttpSession session) {
if (session == activeSession) {
activeSession = null;
}
synchronized (this.sessions) {
this.sessions.remove(session);
}
this.model.removeHttpSession(session);
session.invalidate();
}
/**
* Gets the site.
*
* @return the site
*/
public String getSite() {
return site;
}
/**
* Sets the site.
*
* @param site the new site
*/
public void setSite(String site) {
this.site = site;
}
/**
* Gets the active session.
*
* @return the active session or <code>null</code>, if no session is set as active
* @see #setActiveSession(HttpSession)
*/
public HttpSession getActiveSession() {
return activeSession;
}
/**
* Sets the active session.
*
* @param activeSession the new active session.
* @see #getActiveSession()
* @see #unsetActiveSession()
* @throws IllegalArgumentException If the session provided as parameter is null.
*/
public void setActiveSession(HttpSession activeSession) {
if (log.isInfoEnabled()) {
log.info("Setting new active session for site '" + site + "': " + activeSession);
}
if (activeSession == null) {
throw new IllegalArgumentException(
"When settting an active session, a non-null session has to be provided.");
}
if (this.activeSession == activeSession) {
return;
}
if (this.activeSession != null) {
this.activeSession.setActive(false);
// If the active session was one with no tokens, delete it, as it will probably not
// match anything from this point forward
if (this.activeSession.getTokenValuesCount() == 0) {
this.removeHttpSession(this.activeSession);
} else {
// Notify the model that the session is updated
model.fireHttpSessionUpdated(this.activeSession);
}
}
this.activeSession = activeSession;
activeSession.setActive(true);
// Notify the model that the session is updated
model.fireHttpSessionUpdated(activeSession);
}
/**
* Unset any active session for this site.
*
* @see #setActiveSession(HttpSession)
*/
public void unsetActiveSession() {
if (log.isInfoEnabled()) {
log.info("Setting no active session for site '" + site + "'.");
}
if (this.activeSession != null) {
this.activeSession.setActive(false);
// If the active session was one with no tokens, delete it, at it will probably not
// match anything from this point forward
if (this.activeSession.getTokenValuesCount() == 0) {
this.removeHttpSession(this.activeSession);
} else {
// Notify the model that the session is updated
model.fireHttpSessionUpdated(this.activeSession);
}
this.activeSession = null;
}
}
/**
* Generates a unique session name.
* <p>
* The generated name is guaranteed to be unique compared to existing session names. If a
* generated name is already in use (happens if the user creates a session with a name that is
* equal to the ones generated) a new one will be generated until it's unique.
* <p>
* The generated session name is composed by the (internationalised) word "Session" appended
* with a space character and an (unique sequential) integer identifier. Each time the method is
* called the integer identifier is incremented, at least, by 1 unit.
* <p>
* Example session names generated:
* <p>
*
* <pre>
* Session 0
* Session 1
* Session 2
* </pre>
*
* @return the generated unique session name
* @see #lastGeneratedSessionID
*/
private String generateUniqueSessionName() {
String name;
do {
name = MessageFormat.format(Constant.messages.getString("httpsessions.session.defaultName"),
Integer.valueOf(lastGeneratedSessionID++));
} while (!isSessionNameUnique(name));
return name;
}
/**
* Tells whether the given session {@code name} is unique or not, compared to existing session
* names.
*
* @param name the session name that will be checked
* @return {@code true} if the session name is unique, {@code false} otherwise
* @see #sessions
*/
private boolean isSessionNameUnique(final String name) {
synchronized (this.sessions) {
for (HttpSession session : sessions) {
if (name.equals(session.getName())) {
return false;
}
}
}
return true;
}
/**
* Validates that the session {@code name} is not {@code null} or an empty string.
*
* @param name the session name to be validated
* @throws IllegalArgumentException if the {@code name} is {@code null} or an empty string
*/
private static void validateSessionName(final String name) {
if (name == null) {
throw new IllegalArgumentException("Session name must not be null.");
}
if (name.isEmpty()) {
throw new IllegalArgumentException("Session name must not be empty.");
}
}
/**
* Creates an empty session with the given {@code name} and sets it as the active session.
* <p>
* <strong>Note:</strong> It's responsibility of the caller to ensure that no session with the
* given {@code name} already exists.
*
* @param name the name of the session that will be created and set as the active session
* @throws IllegalArgumentException if the {@code name} is {@code null} or an empty string
* @see #addHttpSession(HttpSession)
* @see #setActiveSession(HttpSession)
* @see #isSessionNameUnique(String)
*/
private void createEmptySessionAndSetAsActive(final String name) {
validateSessionName(name);
final HttpSession session = new HttpSession(name, extension.getHttpSessionTokensSet(getSite()));
addHttpSession(session);
setActiveSession(session);
}
/**
* Creates an empty session with the given {@code name}.
* <p>
* The newly created session is set as the active session.
* <p>
* <strong>Note:</strong> If a session with the given {@code name} already exists no action is
* taken.
*
* @param name the name of the session
* @throws IllegalArgumentException if the {@code name} is {@code null} or an empty string
* @see #setActiveSession(HttpSession)
*/
public void createEmptySession(final String name) {
validateSessionName(name);
if (!isSessionNameUnique(name)) {
return;
}
createEmptySessionAndSetAsActive(name);
}
/**
* Creates a new empty session.
* <p>
* The newly created session is set as the active session.
*
* @see #setActiveSession(HttpSession)
*/
public void createEmptySession() {
createEmptySessionAndSetAsActive(generateUniqueSessionName());
}
/**
* Gets the model.
*
* @return the model
*/
public HttpSessionsTableModel getModel() {
return model;
}
/**
* Process the http request message before being sent.
*
* @param message the message
*/
public void processHttpRequestMessage(HttpMessage message) {
// Get the session tokens for this site
HttpSessionTokensSet siteTokensSet = extension.getHttpSessionTokensSet(getSite());
// No tokens for this site, so no processing
if (siteTokensSet == null) {
log.debug("No session tokens for: " + this.getSite());
return;
}
// Get the matching session, based on the request header
List<HttpCookie> requestCookies = message.getRequestHeader().getHttpCookies();
HttpSession session = getMatchingHttpSession(requestCookies, siteTokensSet);
if (log.isDebugEnabled()) {
log.debug("Matching session for request message (for site " + getSite() + "): " + session);
}
// If any session is active (forced), change the necessary cookies
if (activeSession != null && activeSession != session) {
CookieBasedSessionManagementHelper.processMessageToMatchSession(message, requestCookies,
activeSession);
} else {
if (activeSession == session) {
log.debug("Session of request message is the same as the active session, so no request changes needed.");
} else {
log.debug("No active session is selected.");
}
// Store the session in the HttpMessage for caching purpose
message.setHttpSession(session);
}
}
/**
* Process the http response message received after a request.
*
* @param message the message
*/
public void processHttpResponseMessage(HttpMessage message) {
// Get the session tokens for this site
HttpSessionTokensSet siteTokensSet = extension.getHttpSessionTokensSet(getSite());
// No tokens for this site, so no processing
if (siteTokensSet == null) {
log.debug("No session tokens for: " + this.getSite());
return;
}
// Create an auxiliary map of token values and insert keys for every token
Map<String, Cookie> tokenValues = new HashMap<>();
// Get new values that were set for tokens (e.g. using SET-COOKIE headers), if any
List<HttpCookie> cookiesToSet = message.getResponseHeader().getHttpCookies(message.getRequestHeader().getHostName());
for (HttpCookie cookie : cookiesToSet) {
String lcCookieName = cookie.getName();
if (siteTokensSet.isSessionToken(lcCookieName)) {
try {
// Use 0 if max-age less than -1, Cookie class does not accept negative (expired) max-age (-1 has special
// meaning).
long maxAge = cookie.getMaxAge() < -1 ? 0 : cookie.getMaxAge();
Cookie ck = new Cookie(cookie.getDomain(),lcCookieName,cookie.getValue(),cookie.getPath(),(int) maxAge,cookie.getSecure());
tokenValues.put(lcCookieName, ck);
} catch (IllegalArgumentException e) {
log.warn("Failed to create cookie [" + cookie + "] for site [" + getSite() + "]: " + e.getMessage());
}
}
}
// Get the cookies present in the request
List<HttpCookie> requestCookies = message.getRequestHeader().getHttpCookies();
// XXX When an empty HttpSession is set in the message and the response
// contains session cookies, the empty HttpSession is reused which
// causes the number of messages matched to be incorrect.
// Get the session, based on the request header
HttpSession session = message.getHttpSession();
if (session == null || !session.isValid()) {
session = getMatchingHttpSession(requestCookies, siteTokensSet);
if (log.isDebugEnabled()) {
log.debug("Matching session for response message (from site " + getSite() + "): " + session);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Matching cached session for response message (from site " + getSite() + "): "
+ session);
}
}
// If the session didn't exist, create it now
if (session == null) {
session = new HttpSession(generateUniqueSessionName(),
extension.getHttpSessionTokensSet(getSite()));
this.addHttpSession(session);
// Add all the existing tokens from the request, if they don't replace one in the
// response
for (HttpCookie cookie : requestCookies) {
String cookieName = cookie.getName();
if (siteTokensSet.isSessionToken(cookieName)) {
if (!tokenValues.containsKey(cookieName)) {
// We must ensure that a cookie as always a valid domain and path in order to be able to reuse it.
// HttpClient will discard invalid cookies
String domain = cookie.getDomain();
if (domain == null) {
domain = message.getRequestHeader().getHostName();
}
String path = cookie.getPath();
if (path == null) {
path = "/"; // Default path
}
Cookie ck = new Cookie(domain, cookieName, cookie.getValue(), path, (int) cookie.getMaxAge(), cookie.getSecure());
tokenValues.put(cookieName,ck);
}
}
}
log.info("Created a new session as no match was found: " + session);
}
// Update the session
if (!tokenValues.isEmpty()) {
for (Entry<String, Cookie> tv : tokenValues.entrySet()) {
session.setTokenValue(tv.getKey(), tv.getValue());
}
}
// Update the count of messages matched
session.setMessagesMatched(session.getMessagesMatched() + 1);
this.model.fireHttpSessionUpdated(session);
// Store the session in the HttpMessage for caching purpose
message.setHttpSession(session);
}
/**
* Gets the matching http session for a particular message containing a list of cookies.
*
* @param siteTokens the tokens
* @param cookies the cookies present in the request header of the message
* @return the matching http session, if any, or null if no existing session was found to match
* all the tokens
*/
private HttpSession getMatchingHttpSession(List<HttpCookie> cookies, final HttpSessionTokensSet siteTokens) {
return CookieBasedSessionManagementHelper.getMatchingHttpSession(sessions, cookies, siteTokens);
}
@Override
public String toString() {
return "HttpSessionsSite [site=" + site + ", activeSession=" + activeSession + ", sessions="
+ sessions + "]";
}
/**
* Cleans up the sessions, eliminating the given session token.
*
* @param token the session token
*/
protected void cleanupSessionToken(String token) {
// Empty check
if (sessions.isEmpty()) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Removing duplicates and cleaning up sessions for site - token: " + site + " - "
+ token);
}
synchronized (this.sessions) {
// If there are no more session tokens, delete all sessions
HttpSessionTokensSet siteTokensSet = extension.getHttpSessionTokensSet(site);
if (siteTokensSet == null) {
log.info("No more session tokens. Removing all sessions...");
// Invalidate all sessions
for (HttpSession session : this.sessions) {
session.invalidate();
}
// Remove all sessions
this.sessions.clear();
this.activeSession = null;
this.model.removeAllElements();
return;
}
// Iterate through all the sessions, eliminate the given token and eliminate any duplicates
Map<String, HttpSession> uniqueSession = new HashMap<>(sessions.size());
List<HttpSession> toDelete = new LinkedList<>();
for (HttpSession session : this.sessions) {
// Eliminate the token
session.removeToken(token);
if (session.getTokenValuesCount() == 0 && !session.isActive()) {
toDelete.add(session);
continue;
} else {
model.fireHttpSessionUpdated(session);
}
// If there is already a session with these tokens, mark one of them for deletion
if (uniqueSession.containsKey(session.getTokenValuesString())) {
HttpSession prevSession = uniqueSession.get(session.getTokenValuesString());
// If the latter session is active, put it into the map and delete the other
if (session.isActive()) {
toDelete.add(prevSession);
session.setMessagesMatched(session.getMessagesMatched()
+ prevSession.getMessagesMatched());
} else {
toDelete.add(session);
prevSession.setMessagesMatched(session.getMessagesMatched()
+ prevSession.getMessagesMatched());
}
}
// If it's the first one with these token values, keep it
else {
uniqueSession.put(session.getTokenValuesString(), session);
}
}
// Delete the duplicate sessions
if (log.isInfoEnabled()) {
log.info("Removing duplicate or empty sessions: " + toDelete);
}
Iterator<HttpSession> it = toDelete.iterator();
while (it.hasNext()) {
HttpSession ses = it.next();
ses.invalidate();
sessions.remove(ses);
model.removeHttpSession(ses);
}
}
}
/**
* Gets an unmodifiable set of the http sessions. Attempts to modify the returned set, whether
* direct or via its iterator, result in an UnsupportedOperationException.
*
* @return the http sessions
*/
protected Set<HttpSession> getHttpSessions() {
synchronized (this.sessions) {
return Collections.unmodifiableSet(sessions);
}
}
/**
* Gets the http session with a particular name, if any, or {@code null} otherwise.
*
* @param name the name
* @return the http session with a given name, or null, if no such session exists
*/
protected HttpSession getHttpSession(String name) {
synchronized (this.sessions) {
for (HttpSession session : sessions) {
if (session.getName().equals(name)) {
return session;
}
}
}
return null;
}
/**
* Renames a http session, making sure the new name is unique for the site.
*
* @param oldName the old name
* @param newName the new name
* @return true, if successful
*/
public boolean renameHttpSession(String oldName, String newName) {
// Check new name validity
if (newName == null || newName.isEmpty()) {
log.warn("Trying to rename session from " + oldName + " illegal name: " + newName);
return false;
}
// Check existing old name
HttpSession session = getHttpSession(oldName);
if (session == null) {
return false;
}
// Check new name uniqueness
if (getHttpSession(newName) != null) {
log.warn("Trying to rename session from " + oldName + " to already existing: " + newName);
return false;
}
// Rename the session and notify model
session.setName(newName);
this.model.fireHttpSessionUpdated(session);
return true;
}
static void resetLastGeneratedSessionId() {
lastGeneratedSessionID = 0;
}
}
| src/org/zaproxy/zap/extension/httpsessions/HttpSessionsSite.java | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.httpsessions;
import java.net.HttpCookie;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.httpclient.Cookie;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.session.CookieBasedSessionManagementHelper;
/**
* The Class SiteHttpSessions stores all the information regarding the sessions for a particular
* Site.
*/
public class HttpSessionsSite {
/** The Constant log. */
private static final Logger log = Logger.getLogger(HttpSessionsSite.class);
/** The last session id. */
private static int lastGeneratedSessionID = 0;
/** The extension. */
private ExtensionHttpSessions extension;
/** The site. */
private String site;
/** The sessions as a LinkedHashSet. */
private Set<HttpSession> sessions;
/** The active session. */
private HttpSession activeSession;
/** The model associated with this site. */
private HttpSessionsTableModel model;
/**
* Instantiates a new site http sessions object.
*
* @param extension the extension
* @param site the site
*/
public HttpSessionsSite(ExtensionHttpSessions extension, String site) {
super();
this.extension = extension;
this.site = site;
this.sessions = new LinkedHashSet<>();
this.model = new HttpSessionsTableModel(this);
this.activeSession = null;
}
/**
* Adds a new http session to this site.
*
* @param session the session
*/
public void addHttpSession(HttpSession session) {
synchronized (this.sessions) {
this.sessions.add(session);
}
this.model.addHttpSession(session);
}
/**
* Removes an existing session.
*
* @param session the session
*/
public void removeHttpSession(HttpSession session) {
if (session == activeSession) {
activeSession = null;
}
synchronized (this.sessions) {
this.sessions.remove(session);
}
this.model.removeHttpSession(session);
session.invalidate();
}
/**
* Gets the site.
*
* @return the site
*/
public String getSite() {
return site;
}
/**
* Sets the site.
*
* @param site the new site
*/
public void setSite(String site) {
this.site = site;
}
/**
* Gets the active session.
*
* @return the active session or <code>null</code>, if no session is set as active
* @see #setActiveSession(HttpSession)
*/
public HttpSession getActiveSession() {
return activeSession;
}
/**
* Sets the active session.
*
* @param activeSession the new active session.
* @see #getActiveSession()
* @see #unsetActiveSession()
* @throws IllegalArgumentException If the session provided as parameter is null.
*/
public void setActiveSession(HttpSession activeSession) {
if (log.isInfoEnabled()) {
log.info("Setting new active session for site '" + site + "': " + activeSession);
}
if (activeSession == null) {
throw new IllegalArgumentException(
"When settting an active session, a non-null session has to be provided.");
}
if (this.activeSession == activeSession) {
return;
}
if (this.activeSession != null) {
this.activeSession.setActive(false);
// If the active session was one with no tokens, delete it, as it will probably not
// match anything from this point forward
if (this.activeSession.getTokenValuesCount() == 0) {
this.removeHttpSession(this.activeSession);
} else {
// Notify the model that the session is updated
model.fireHttpSessionUpdated(this.activeSession);
}
}
this.activeSession = activeSession;
activeSession.setActive(true);
// Notify the model that the session is updated
model.fireHttpSessionUpdated(activeSession);
}
/**
* Unset any active session for this site.
*
* @see #setActiveSession(HttpSession)
*/
public void unsetActiveSession() {
if (log.isInfoEnabled()) {
log.info("Setting no active session for site '" + site + "'.");
}
if (this.activeSession != null) {
this.activeSession.setActive(false);
// If the active session was one with no tokens, delete it, at it will probably not
// match anything from this point forward
if (this.activeSession.getTokenValuesCount() == 0) {
this.removeHttpSession(this.activeSession);
} else {
// Notify the model that the session is updated
model.fireHttpSessionUpdated(this.activeSession);
}
this.activeSession = null;
}
}
/**
* Generates a unique session name.
* <p>
* The generated name is guaranteed to be unique compared to existing session names. If a
* generated name is already in use (happens if the user creates a session with a name that is
* equal to the ones generated) a new one will be generated until it's unique.
* <p>
* The generated session name is composed by the (internationalised) word "Session" appended
* with a space character and an (unique sequential) integer identifier. Each time the method is
* called the integer identifier is incremented, at least, by 1 unit.
* <p>
* Example session names generated:
* <p>
*
* <pre>
* Session 0
* Session 1
* Session 2
* </pre>
*
* @return the generated unique session name
* @see #lastGeneratedSessionID
*/
private String generateUniqueSessionName() {
String name;
do {
name = MessageFormat.format(Constant.messages.getString("httpsessions.session.defaultName"),
Integer.valueOf(lastGeneratedSessionID++));
} while (!isSessionNameUnique(name));
return name;
}
/**
* Tells whether the given session {@code name} is unique or not, compared to existing session
* names.
*
* @param name the session name that will be checked
* @return {@code true} if the session name is unique, {@code false} otherwise
* @see #sessions
*/
private boolean isSessionNameUnique(final String name) {
synchronized (this.sessions) {
for (HttpSession session : sessions) {
if (name.equals(session.getName())) {
return false;
}
}
}
return true;
}
/**
* Validates that the session {@code name} is not {@code null} or an empty string.
*
* @param name the session name to be validated
* @throws IllegalArgumentException if the {@code name} is {@code null} or an empty string
*/
private static void validateSessionName(final String name) {
if (name == null) {
throw new IllegalArgumentException("Session name must not be null.");
}
if (name.isEmpty()) {
throw new IllegalArgumentException("Session name must not be empty.");
}
}
/**
* Creates an empty session with the given {@code name} and sets it as the active session.
* <p>
* <strong>Note:</strong> It's responsibility of the caller to ensure that no session with the
* given {@code name} already exists.
*
* @param name the name of the session that will be created and set as the active session
* @throws IllegalArgumentException if the {@code name} is {@code null} or an empty string
* @see #addHttpSession(HttpSession)
* @see #setActiveSession(HttpSession)
* @see #isSessionNameUnique(String)
*/
private void createEmptySessionAndSetAsActive(final String name) {
validateSessionName(name);
final HttpSession session = new HttpSession(name, extension.getHttpSessionTokensSet(getSite()));
addHttpSession(session);
setActiveSession(session);
}
/**
* Creates an empty session with the given {@code name}.
* <p>
* The newly created session is set as the active session.
* <p>
* <strong>Note:</strong> If a session with the given {@code name} already exists no action is
* taken.
*
* @param name the name of the session
* @throws IllegalArgumentException if the {@code name} is {@code null} or an empty string
* @see #setActiveSession(HttpSession)
*/
public void createEmptySession(final String name) {
validateSessionName(name);
if (!isSessionNameUnique(name)) {
return;
}
createEmptySessionAndSetAsActive(name);
}
/**
* Creates a new empty session.
* <p>
* The newly created session is set as the active session.
*
* @see #setActiveSession(HttpSession)
*/
public void createEmptySession() {
createEmptySessionAndSetAsActive(generateUniqueSessionName());
}
/**
* Gets the model.
*
* @return the model
*/
public HttpSessionsTableModel getModel() {
return model;
}
/**
* Process the http request message before being sent.
*
* @param message the message
*/
public void processHttpRequestMessage(HttpMessage message) {
// Get the session tokens for this site
HttpSessionTokensSet siteTokensSet = extension.getHttpSessionTokensSet(getSite());
// No tokens for this site, so no processing
if (siteTokensSet == null) {
log.debug("No session tokens for: " + this.getSite());
return;
}
// Get the matching session, based on the request header
List<HttpCookie> requestCookies = message.getRequestHeader().getHttpCookies();
HttpSession session = getMatchingHttpSession(requestCookies, siteTokensSet);
if (log.isDebugEnabled()) {
log.debug("Matching session for request message (for site " + getSite() + "): " + session);
}
// If any session is active (forced), change the necessary cookies
if (activeSession != null && activeSession != session) {
CookieBasedSessionManagementHelper.processMessageToMatchSession(message, requestCookies,
activeSession);
} else {
if (activeSession == session) {
log.debug("Session of request message is the same as the active session, so no request changes needed.");
} else {
log.debug("No active session is selected.");
}
// Store the session in the HttpMessage for caching purpose
message.setHttpSession(session);
}
}
/**
* Process the http response message received after a request.
*
* @param message the message
*/
public void processHttpResponseMessage(HttpMessage message) {
// Get the session tokens for this site
HttpSessionTokensSet siteTokensSet = extension.getHttpSessionTokensSet(getSite());
// No tokens for this site, so no processing
if (siteTokensSet == null) {
log.debug("No session tokens for: " + this.getSite());
return;
}
// Create an auxiliary map of token values and insert keys for every token
Map<String, Cookie> tokenValues = new HashMap<>();
// Get new values that were set for tokens (e.g. using SET-COOKIE headers), if any
List<HttpCookie> cookiesToSet = message.getResponseHeader().getHttpCookies(message.getRequestHeader().getHostName());
for (HttpCookie cookie : cookiesToSet) {
String lcCookieName = cookie.getName();
if (siteTokensSet.isSessionToken(lcCookieName)) {
Cookie ck = new Cookie(cookie.getDomain(),lcCookieName,cookie.getValue(),cookie.getPath(),(int) cookie.getMaxAge(),cookie.getSecure());
tokenValues.put(lcCookieName, ck);
}
}
// Get the cookies present in the request
List<HttpCookie> requestCookies = message.getRequestHeader().getHttpCookies();
// XXX When an empty HttpSession is set in the message and the response
// contains session cookies, the empty HttpSession is reused which
// causes the number of messages matched to be incorrect.
// Get the session, based on the request header
HttpSession session = message.getHttpSession();
if (session == null || !session.isValid()) {
session = getMatchingHttpSession(requestCookies, siteTokensSet);
if (log.isDebugEnabled()) {
log.debug("Matching session for response message (from site " + getSite() + "): " + session);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Matching cached session for response message (from site " + getSite() + "): "
+ session);
}
}
// If the session didn't exist, create it now
if (session == null) {
session = new HttpSession(generateUniqueSessionName(),
extension.getHttpSessionTokensSet(getSite()));
this.addHttpSession(session);
// Add all the existing tokens from the request, if they don't replace one in the
// response
for (HttpCookie cookie : requestCookies) {
String cookieName = cookie.getName();
if (siteTokensSet.isSessionToken(cookieName)) {
if (!tokenValues.containsKey(cookieName)) {
// We must ensure that a cookie as always a valid domain and path in order to be able to reuse it.
// HttpClient will discard invalid cookies
String domain = cookie.getDomain();
if (domain == null) {
domain = message.getRequestHeader().getHostName();
}
String path = cookie.getPath();
if (path == null) {
path = "/"; // Default path
}
Cookie ck = new Cookie(domain, cookieName, cookie.getValue(), path, (int) cookie.getMaxAge(), cookie.getSecure());
tokenValues.put(cookieName,ck);
}
}
}
log.info("Created a new session as no match was found: " + session);
}
// Update the session
if (!tokenValues.isEmpty()) {
for (Entry<String, Cookie> tv : tokenValues.entrySet()) {
session.setTokenValue(tv.getKey(), tv.getValue());
}
}
// Update the count of messages matched
session.setMessagesMatched(session.getMessagesMatched() + 1);
this.model.fireHttpSessionUpdated(session);
// Store the session in the HttpMessage for caching purpose
message.setHttpSession(session);
}
/**
* Gets the matching http session for a particular message containing a list of cookies.
*
* @param siteTokens the tokens
* @param cookies the cookies present in the request header of the message
* @return the matching http session, if any, or null if no existing session was found to match
* all the tokens
*/
private HttpSession getMatchingHttpSession(List<HttpCookie> cookies, final HttpSessionTokensSet siteTokens) {
return CookieBasedSessionManagementHelper.getMatchingHttpSession(sessions, cookies, siteTokens);
}
@Override
public String toString() {
return "HttpSessionsSite [site=" + site + ", activeSession=" + activeSession + ", sessions="
+ sessions + "]";
}
/**
* Cleans up the sessions, eliminating the given session token.
*
* @param token the session token
*/
protected void cleanupSessionToken(String token) {
// Empty check
if (sessions.isEmpty()) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Removing duplicates and cleaning up sessions for site - token: " + site + " - "
+ token);
}
synchronized (this.sessions) {
// If there are no more session tokens, delete all sessions
HttpSessionTokensSet siteTokensSet = extension.getHttpSessionTokensSet(site);
if (siteTokensSet == null) {
log.info("No more session tokens. Removing all sessions...");
// Invalidate all sessions
for (HttpSession session : this.sessions) {
session.invalidate();
}
// Remove all sessions
this.sessions.clear();
this.activeSession = null;
this.model.removeAllElements();
return;
}
// Iterate through all the sessions, eliminate the given token and eliminate any duplicates
Map<String, HttpSession> uniqueSession = new HashMap<>(sessions.size());
List<HttpSession> toDelete = new LinkedList<>();
for (HttpSession session : this.sessions) {
// Eliminate the token
session.removeToken(token);
if (session.getTokenValuesCount() == 0 && !session.isActive()) {
toDelete.add(session);
continue;
} else {
model.fireHttpSessionUpdated(session);
}
// If there is already a session with these tokens, mark one of them for deletion
if (uniqueSession.containsKey(session.getTokenValuesString())) {
HttpSession prevSession = uniqueSession.get(session.getTokenValuesString());
// If the latter session is active, put it into the map and delete the other
if (session.isActive()) {
toDelete.add(prevSession);
session.setMessagesMatched(session.getMessagesMatched()
+ prevSession.getMessagesMatched());
} else {
toDelete.add(session);
prevSession.setMessagesMatched(session.getMessagesMatched()
+ prevSession.getMessagesMatched());
}
}
// If it's the first one with these token values, keep it
else {
uniqueSession.put(session.getTokenValuesString(), session);
}
}
// Delete the duplicate sessions
if (log.isInfoEnabled()) {
log.info("Removing duplicate or empty sessions: " + toDelete);
}
Iterator<HttpSession> it = toDelete.iterator();
while (it.hasNext()) {
HttpSession ses = it.next();
ses.invalidate();
sessions.remove(ses);
model.removeHttpSession(ses);
}
}
}
/**
* Gets an unmodifiable set of the http sessions. Attempts to modify the returned set, whether
* direct or via its iterator, result in an UnsupportedOperationException.
*
* @return the http sessions
*/
protected Set<HttpSession> getHttpSessions() {
synchronized (this.sessions) {
return Collections.unmodifiableSet(sessions);
}
}
/**
* Gets the http session with a particular name, if any, or {@code null} otherwise.
*
* @param name the name
* @return the http session with a given name, or null, if no such session exists
*/
protected HttpSession getHttpSession(String name) {
synchronized (this.sessions) {
for (HttpSession session : sessions) {
if (session.getName().equals(name)) {
return session;
}
}
}
return null;
}
/**
* Renames a http session, making sure the new name is unique for the site.
*
* @param oldName the old name
* @param newName the new name
* @return true, if successful
*/
public boolean renameHttpSession(String oldName, String newName) {
// Check new name validity
if (newName == null || newName.isEmpty()) {
log.warn("Trying to rename session from " + oldName + " illegal name: " + newName);
return false;
}
// Check existing old name
HttpSession session = getHttpSession(oldName);
if (session == null) {
return false;
}
// Check new name uniqueness
if (getHttpSession(newName) != null) {
log.warn("Trying to rename session from " + oldName + " to already existing: " + newName);
return false;
}
// Rename the session and notify model
session.setName(newName);
this.model.fireHttpSessionUpdated(session);
return true;
}
static void resetLastGeneratedSessionId() {
lastGeneratedSessionID = 0;
}
}
| Change HttpSessionsSite to better handle expired cookies (max-age < 0)
Change method HttpSessionsSite.processHttpResponseMessage(HttpMessage)
to use max-age as 0 (expired) when the cookie has a negative max-age
(rfc6265, 5.2.2), class Cookie does not accept negative max-age (note,
the check uses -1 instead of 0 because the former value has a special
meaning). Also, catch exception thrown by Cookie class to prevent other
cookie "errors" from being handled by other unrelated classes (like
HttpSender class).
Fix #2226 - ZAP should handle HttpSessionsSite's cookie errors more
gracefully
| src/org/zaproxy/zap/extension/httpsessions/HttpSessionsSite.java | Change HttpSessionsSite to better handle expired cookies (max-age < 0) |
|
Java | apache-2.0 | 09289b73a194eeb231571da70849254179d1ff19 | 0 | nicopico-dev/dashclock-birthday | /*
* Copyright 2013 Nicolas Picon <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.nicopico.dashclock.birthday;
import fr.nicopico.dashclock.birthday.data.Birthday;
import fr.nicopico.dashclock.birthday.data.BirthdayRetriever;
import org.joda.time.DateTime;
import org.joda.time.DateTimeFieldType;
import org.joda.time.Days;
import java.util.List;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
/**
* User: Nicolas PICON
* Date: 24/08/13 - 17:22
*/
public class BirthdayService extends DashClockExtension {
public static final String PREF_DAYS_LIMIT_KEY = "pref_days_limit";
private BirthdayRetriever birthdayRetriever;
private int daysLimit;
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
birthdayRetriever = new BirthdayRetriever();
updatePreferences();
// Listen for contact update
//noinspection ConstantConditions
addWatchContentUris(new String[] {
ContactsContract.Contacts.CONTENT_URI.toString()
});
}
@SuppressWarnings("ConstantConditions")
private void updatePreferences() {
final SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
daysLimit = Integer.valueOf(sharedPreferences.getString(PREF_DAYS_LIMIT_KEY, "7"));
}
@Override
protected void onUpdateData(int reason) {
final List<Birthday> birthdays = birthdayRetriever.getContactWithBirthdays(getApplicationContext());
final Resources res = getResources();
if (reason == UPDATE_REASON_SETTINGS_CHANGED) {
updatePreferences();
}
if (birthdays.size() > 0) {
Birthday birthday = birthdays.get(0);
DateTime today = new DateTime();
DateTime birthdayEvent = birthday.birthdayDate.toDateTime(today);
int days;
if (birthdayEvent.isAfter(today) || birthdayEvent.isEqual(today)) {
days = Days.daysBetween(today, birthdayEvent).getDays();
}
else {
// Next birthday event is next year
days = Days.daysBetween(today, birthdayEvent.plusYears(1)).getDays();
}
if (days > daysLimit) {
publishUpdate(new ExtensionData().visible(false));
return;
}
StringBuilder body = new StringBuilder();
// Age
if (!birthday.unknownYear) {
int age = today.get(DateTimeFieldType.year()) - birthday.year;
body.append(res.getString(R.string.age_format, age));
body.append(' ');
}
// When
int daysFormatResId;
switch (days) {
case 0:
daysFormatResId = R.string.when_today_format;
break;
case 1:
daysFormatResId = R.string.when_tomorrow_format;
break;
default:
daysFormatResId = R.string.when_days_format;
}
body.append(res.getString(daysFormatResId, days));
// Open QuickContact dialog on click
Intent contactIntent = QuickContactProxy.buildIntent(getApplicationContext(), birthday.lookupKey);
// Display message
publishUpdate(
new ExtensionData()
.visible(true)
.icon(R.drawable.ic_extension_white)
.status(birthday.displayName)
.expandedTitle(res.getString(R.string.title_format, birthday.displayName))
.expandedBody(body.toString())
.clickIntent(contactIntent)
);
}
else {
// No upcoming birthday
publishUpdate(new ExtensionData().visible(false));
}
}
}
| src/fr/nicopico/dashclock/birthday/BirthdayService.java | /*
* Copyright 2013 Nicolas Picon <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.nicopico.dashclock.birthday;
import fr.nicopico.dashclock.birthday.data.Birthday;
import fr.nicopico.dashclock.birthday.data.BirthdayRetriever;
import org.joda.time.DateTime;
import org.joda.time.DateTimeFieldType;
import org.joda.time.Days;
import java.util.List;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
/**
* User: Nicolas PICON
* Date: 24/08/13 - 17:22
*/
public class BirthdayService extends DashClockExtension {
public static final String PREF_DAYS_LIMIT_KEY = "pref_days_limit";
private BirthdayRetriever birthdayRetriever;
private int daysLimit;
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
birthdayRetriever = new BirthdayRetriever();
updatePreferences();
// Listen for contact update
//noinspection ConstantConditions
addWatchContentUris(new String[] {
ContactsContract.Contacts.CONTENT_URI.toString()
});
}
@SuppressWarnings("ConstantConditions")
private void updatePreferences() {
final SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
daysLimit = Integer.valueOf(sharedPreferences.getString(PREF_DAYS_LIMIT_KEY, "7"));
}
@Override
protected void onUpdateData(int reason) {
final List<Birthday> birthdays = birthdayRetriever.getContactWithBirthdays(getApplicationContext());
final Resources res = getResources();
if (reason == UPDATE_REASON_SETTINGS_CHANGED) {
updatePreferences();
}
if (birthdays.size() > 0) {
Birthday birthday = birthdays.get(0);
DateTime today = new DateTime();
DateTime birthdayEvent = birthday.birthdayDate.toDateTime(today);
int days;
if (birthdayEvent.isAfter(today)) {
days = Days.daysBetween(today, birthdayEvent).getDays();
}
else {
// Next birthday event is next year
days = Days.daysBetween(today, birthdayEvent.plusYears(1)).getDays();
}
if (days > daysLimit) {
publishUpdate(new ExtensionData().visible(false));
return;
}
StringBuilder body = new StringBuilder();
// Age
if (!birthday.unknownYear) {
int age = today.get(DateTimeFieldType.year()) - birthday.year;
body.append(res.getString(R.string.age_format, age));
body.append(' ');
}
// When
int daysFormatResId;
switch (days) {
case 0:
daysFormatResId = R.string.when_today_format;
break;
case 1:
daysFormatResId = R.string.when_tomorrow_format;
break;
default:
daysFormatResId = R.string.when_days_format;
}
body.append(res.getString(daysFormatResId, days));
// Open QuickContact dialog on click
Intent contactIntent = QuickContactProxy.buildIntent(getApplicationContext(), birthday.lookupKey);
// Display message
publishUpdate(
new ExtensionData()
.visible(true)
.icon(R.drawable.ic_extension_white)
.status(birthday.displayName)
.expandedTitle(res.getString(R.string.title_format, birthday.displayName))
.expandedBody(body.toString())
.clickIntent(contactIntent)
);
}
else {
// No upcoming birthday
publishUpdate(new ExtensionData().visible(false));
}
}
}
| Bug fix: today's birthday are not displayed
| src/fr/nicopico/dashclock/birthday/BirthdayService.java | Bug fix: today's birthday are not displayed |
|
Java | apache-2.0 | 5180b2c05621d5e48101492b0b2522311f775f89 | 0 | anuragkh/annotation-search,anuragkh/annotation-search | package com.elsevier.cat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.Text;
/**
* Wrapper for ArrayWritable
* This is needed so we can persist the array to S3.
*
* @author mcbeathd
*/
public class StringArrayWritable extends ArrayWritable {
// Logger
private static Log log = LogFactory.getLog(StringArrayWritable.class);
public StringArrayWritable() {
super(Text.class);
}
public StringArrayWritable(String[] strings) {
super(Text.class);
Text[] texts = new Text[strings.length];
for (int i = 0; i < strings.length; i++) {
texts[i] = new Text(strings[i]);
}
set(texts);
}
}
| src/main/java/com/elsevier/cat/StringArrayWritable.java | package com.elsevier.cat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.Text;
/**
* Wrapper for ArrayWritable
* This is needed so we can persist the array to S3.
*
* @author mcbeathd
*
*/
public class StringArrayWritable extends ArrayWritable {
// Logger
private static Log log = LogFactory.getLog(StringArrayWritable.class);
public StringArrayWritable() { super(Text.class); }
public StringArrayWritable(String[] strings) {
super(Text.class);
Text[] texts = new Text[strings.length];
for (int i = 0; i < strings.length; i++) {
texts[i] = new Text(strings[i]);
}
set(texts);
}
}
| Fixed formatting
| src/main/java/com/elsevier/cat/StringArrayWritable.java | Fixed formatting |
|
Java | apache-2.0 | 4671012a6a0ff31a555916b9425a61fb07bc5bbc | 0 | jdahlstrom/vaadin.react,sitexa/vaadin,Peppe/vaadin,mittop/vaadin,Darsstar/framework,shahrzadmn/vaadin,udayinfy/vaadin,oalles/vaadin,carrchang/vaadin,kironapublic/vaadin,Legioth/vaadin,mstahv/framework,Peppe/vaadin,peterl1084/framework,jdahlstrom/vaadin.react,sitexa/vaadin,mstahv/framework,udayinfy/vaadin,Legioth/vaadin,magi42/vaadin,mstahv/framework,shahrzadmn/vaadin,asashour/framework,asashour/framework,travisfw/vaadin,fireflyc/vaadin,bmitc/vaadin,udayinfy/vaadin,magi42/vaadin,Flamenco/vaadin,synes/vaadin,jdahlstrom/vaadin.react,Darsstar/framework,mittop/vaadin,asashour/framework,Peppe/vaadin,magi42/vaadin,magi42/vaadin,Scarlethue/vaadin,cbmeeks/vaadin,Legioth/vaadin,mittop/vaadin,Darsstar/framework,oalles/vaadin,mittop/vaadin,Scarlethue/vaadin,travisfw/vaadin,sitexa/vaadin,shahrzadmn/vaadin,Scarlethue/vaadin,Scarlethue/vaadin,oalles/vaadin,fireflyc/vaadin,oalles/vaadin,jdahlstrom/vaadin.react,bmitc/vaadin,shahrzadmn/vaadin,Flamenco/vaadin,synes/vaadin,peterl1084/framework,carrchang/vaadin,bmitc/vaadin,sitexa/vaadin,cbmeeks/vaadin,kironapublic/vaadin,peterl1084/framework,carrchang/vaadin,fireflyc/vaadin,mstahv/framework,bmitc/vaadin,synes/vaadin,Flamenco/vaadin,peterl1084/framework,Peppe/vaadin,oalles/vaadin,Darsstar/framework,asashour/framework,mstahv/framework,sitexa/vaadin,peterl1084/framework,synes/vaadin,kironapublic/vaadin,carrchang/vaadin,shahrzadmn/vaadin,Scarlethue/vaadin,cbmeeks/vaadin,Legioth/vaadin,Legioth/vaadin,udayinfy/vaadin,travisfw/vaadin,Peppe/vaadin,magi42/vaadin,Flamenco/vaadin,travisfw/vaadin,fireflyc/vaadin,asashour/framework,jdahlstrom/vaadin.react,synes/vaadin,kironapublic/vaadin,fireflyc/vaadin,travisfw/vaadin,Darsstar/framework,cbmeeks/vaadin,kironapublic/vaadin,udayinfy/vaadin | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowCloseListener;
import com.google.gwt.user.client.impl.HTTPRequestImpl;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.RenderInformation.FloatSize;
import com.itmill.toolkit.terminal.gwt.client.RenderInformation.Size;
import com.itmill.toolkit.terminal.gwt.client.ui.Field;
import com.itmill.toolkit.terminal.gwt.client.ui.IContextMenu;
import com.itmill.toolkit.terminal.gwt.client.ui.INotification;
import com.itmill.toolkit.terminal.gwt.client.ui.IView;
import com.itmill.toolkit.terminal.gwt.client.ui.INotification.HideEvent;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class ApplicationConnection {
private static final String MODIFIED_CLASSNAME = "i-modified";
private static final String REQUIRED_CLASSNAME_EXT = "-required";
private static final String ERROR_CLASSNAME_EXT = "-error";
public static final String VAR_RECORD_SEPARATOR = "\u001e";
public static final String VAR_FIELD_SEPARATOR = "\u001f";
public static final String VAR_BURST_SEPARATOR = "\u001d";
public static final String UIDL_SECURITY_HEADER = "com.itmill.seckey";
private static String uidl_security_key = "init";
private final HashMap resourcesMap = new HashMap();
private static Console console;
private static boolean testingMode;
private final Vector pendingVariables = new Vector();
private final HashMap<String, Paintable> idToPaintable = new HashMap<String, Paintable>();
private final HashMap<Paintable, String> paintableToId = new HashMap<Paintable, String>();
/** Contains ExtendedTitleInfo by paintable id */
private final HashMap<Paintable, TooltipInfo> paintableToTitle = new HashMap<Paintable, TooltipInfo>();
private final HashMap<Widget, FloatSize> componentRelativeSizes = new HashMap<Widget, FloatSize>();
private final HashMap<Widget, Size> componentOffsetSizes = new HashMap<Widget, Size>();
private final WidgetSet widgetSet;
private IContextMenu contextMenu = null;
private Timer loadTimer;
private Timer loadTimer2;
private Timer loadTimer3;
private Element loadElement;
private final IView view;
private boolean applicationRunning = false;
/**
* True if each Paintable objects id is injected to DOM. Used for Testing
* Tools.
*/
private boolean usePaintableIdsInDOM = false;
/**
* Contains reference for client wrapper given to Testing Tools.
*
* Used in JSNI functions
*
*/
@SuppressWarnings("unused")
private final JavaScriptObject ttClientWrapper = null;
private int activeRequests = 0;
/** Parameters for this application connection loaded from the web-page */
private final ApplicationConfiguration configuration;
/** List of pending variable change bursts that must be submitted in order */
private final Vector pendingVariableBursts = new Vector();
/** Timer for automatic refirect to SessionExpiredURL */
private Timer redirectTimer;
/** redirectTimer scheduling interval in seconds */
private int sessionExpirationInterval;
private ArrayList<Paintable> relativeSizeChanges = new ArrayList<Paintable>();;
private ArrayList<Paintable> componentCaptionSizeChanges = new ArrayList<Paintable>();;
private Date requestStartTime;
private boolean validatingLayouts = false;
private Set<Paintable> zeroWidthComponents = null;
private Set<Paintable> zeroHeightComponents = null;
public ApplicationConnection(WidgetSet widgetSet,
ApplicationConfiguration cnf) {
this.widgetSet = widgetSet;
configuration = cnf;
if (isDebugMode()) {
console = new IDebugConsole(this, cnf, !isQuietDebugMode());
} else {
console = new NullConsole();
}
if (checkTestingMode()) {
usePaintableIdsInDOM = true;
initializeTestingTools();
Window.addWindowCloseListener(new WindowCloseListener() {
public void onWindowClosed() {
uninitializeTestingTools();
}
public String onWindowClosing() {
return null;
}
});
}
initializeClientHooks();
view = new IView(cnf.getRootPanelId());
showLoadingIndicator();
}
/**
* Starts this application. Don't call this method directly - it's called by
* {@link ApplicationConfiguration#startNextApplication()}, which should be
* called once this application has started (first response received) or
* failed to start. This ensures that the applications are started in order,
* to avoid session-id problems.
*/
void start() {
makeUidlRequest("", true, false, false);
}
/**
* Method to check if application is in testing mode. Can be used after
* application init.
*
* @return true if in testing mode
*/
public static boolean isTestingMode() {
return testingMode;
}
/**
* Check is application is run in testing mode.
*
* @return true if in testing mode
*/
private native static boolean checkTestingMode()
/*-{
try {
@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::testingMode = $wnd.top.itmill && $wnd.top.itmill.registerToTT ? true : false;
return @com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::testingMode;
} catch(e) {
// if run in iframe SOP may cause exception, return false then
return false;
}
}-*/;
private native void initializeTestingTools()
/*-{
var ap = this;
var client = {};
client.isActive = function() {
return [email protected]::hasActiveRequest()();
}
var vi = [email protected]::getVersionInfo()();
if (vi) {
client.getVersionInfo = function() {
return vi;
}
}
$wnd.top.itmill.registerToTT(client);
this.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::ttClientWrapper = client;
}-*/;
/**
* Helper for tt initialization
*/
@SuppressWarnings("unused")
private JavaScriptObject getVersionInfo() {
return configuration.getVersionInfoJSObject();
}
private native void uninitializeTestingTools()
/*-{
$wnd.top.itmill.unregisterFromTT(this.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::ttClientWrapper);
}-*/;
/**
* Publishes a JavaScript API for mash-up applications.
* <ul>
* <li><code>itmill.forceSync()</code> sends pending variable changes, in
* effect synchronizing the server and client state. This is done for all
* applications on host page.</li>
* </ul>
*
* TODO make this multi-app aware
*/
private native void initializeClientHooks()
/*-{
var app = this;
var oldSync;
if($wnd.itmill.forceSync) {
oldSync = $wnd.itmill.forceSync;
}
$wnd.itmill.forceSync = function() {
if(oldSync) {
oldSync();
}
app.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::sendPendingVariableChanges()();
}
var oldForceLayout;
if($wnd.itmill.forceLayout) {
oldForceLayout = $wnd.itmill.forceLayout;
}
$wnd.itmill.forceLayout = function() {
if(oldForceLayout) {
oldForceLayout();
}
app.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::forceLayout()();
}
}-*/;
public static Console getConsole() {
return console;
}
private native static boolean isDebugMode()
/*-{
if($wnd.itmill.debug) {
var parameters = $wnd.location.search;
var re = /debug[^\/]*$/;
return re.test(parameters);
} else {
return false;
}
}-*/;
private native static boolean isQuietDebugMode()
/*-{
var uri = $wnd.location;
var re = /debug=q[^\/]*$/;
return re.test(uri);
}-*/;
public String getAppUri() {
return configuration.getApplicationUri();
};
public boolean hasActiveRequest() {
return (activeRequests > 0);
}
private void makeUidlRequest(String requestData, boolean repaintAll,
boolean forceSync, boolean analyzeLayouts) {
startRequest();
// Security: double cookie submission pattern
requestData = uidl_security_key + VAR_BURST_SEPARATOR + requestData;
console.log("Making UIDL Request with params: " + requestData);
String uri = getAppUri() + "UIDL" + configuration.getPathInfo();
if (repaintAll) {
uri += "?repaintAll=1";
if (analyzeLayouts) {
uri += "&analyzeLayouts=1";
}
}
if (windowName != null && windowName.length() > 0) {
uri += (repaintAll ? "&" : "?") + "windowName=" + windowName;
}
if (!forceSync) {
final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
uri);
rb.setHeader("Content-Type", "text/plain;charset=utf-8");
try {
rb.sendRequest(requestData, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// TODO Better reporting to user
console.error("Got error");
endRequest();
if (!applicationRunning) {
// start failed, let's try to start the next app
ApplicationConfiguration.startNextApplication();
}
}
public void onResponseReceived(Request request,
Response response) {
if ("init".equals(uidl_security_key)) {
// Read security key
String key = response
.getHeader(UIDL_SECURITY_HEADER);
if (null != key) {
uidl_security_key = key;
}
}
console.log("Server visit took "
+ String.valueOf((new Date()).getTime()
- requestStartTime.getTime()) + "ms");
if (applicationRunning) {
handleReceivedJSONMessage(response);
} else {
applicationRunning = true;
handleWhenCSSLoaded(response);
ApplicationConfiguration.startNextApplication();
}
}
int cssWaits = 0;
static final int MAX_CSS_WAITS = 20;
private void handleWhenCSSLoaded(final Response response) {
int heightOfLoadElement = DOM.getElementPropertyInt(
loadElement, "offsetHeight");
if (heightOfLoadElement == 0
&& cssWaits < MAX_CSS_WAITS) {
(new Timer() {
@Override
public void run() {
handleWhenCSSLoaded(response);
}
}).schedule(50);
console
.log("Assuming CSS loading is not complete, "
+ "postponing render phase. "
+ "(.i-loading-indicator height == 0)");
cssWaits++;
} else {
handleReceivedJSONMessage(response);
if (cssWaits >= MAX_CSS_WAITS) {
console
.error("CSS files may have not loaded properly.");
}
}
}
});
} catch (final RequestException e) {
ClientExceptionHandler.displayError(e);
endRequest();
}
} else {
// Synchronized call, discarded response
syncSendForce(((HTTPRequestImpl) GWT.create(HTTPRequestImpl.class))
.createXmlHTTPRequest(), uri, requestData);
}
}
private native void syncSendForce(JavaScriptObject xmlHttpRequest,
String uri, String requestData)
/*-{
try {
xmlHttpRequest.open("POST", uri, false);
xmlHttpRequest.setRequestHeader("Content-Type", "text/plain;charset=utf-8");
xmlHttpRequest.send(requestData);
} catch (e) {
// No errors are managed as this is synchronous forceful send that can just fail
}
}-*/;
private void startRequest() {
activeRequests++;
requestStartTime = new Date();
// show initial throbber
if (loadTimer == null) {
loadTimer = new Timer() {
@Override
public void run() {
/*
* IE7 does not properly cancel the event with
* loadTimer.cancel() so we have to check that we really
* should make it visible
*/
if (loadTimer != null) {
showLoadingIndicator();
}
}
};
// First one kicks in at 300ms
}
loadTimer.schedule(300);
}
private void endRequest() {
checkForPendingVariableBursts();
activeRequests--;
// deferring to avoid flickering
DeferredCommand.addCommand(new Command() {
public void execute() {
if (activeRequests == 0) {
hideLoadingIndicator();
}
}
});
}
/**
* This method is called after applying uidl change set to application.
*
* It will clean current and queued variable change sets. And send next
* change set if it exists.
*/
private void checkForPendingVariableBursts() {
cleanVariableBurst(pendingVariables);
if (pendingVariableBursts.size() > 0) {
for (Iterator iterator = pendingVariableBursts.iterator(); iterator
.hasNext();) {
cleanVariableBurst((Vector) iterator.next());
}
Vector nextBurst = (Vector) pendingVariableBursts.firstElement();
pendingVariableBursts.remove(0);
buildAndSendVariableBurst(nextBurst, false);
}
}
/**
* Cleans given queue of variable changes of such changes that came from
* components that do not exist anymore.
*
* @param variableBurst
*/
private void cleanVariableBurst(Vector variableBurst) {
for (int i = 1; i < variableBurst.size(); i += 2) {
String id = (String) variableBurst.get(i);
id = id.substring(0, id.indexOf(VAR_FIELD_SEPARATOR));
if (!idToPaintable.containsKey(id)) {
// variable owner does not exist anymore
variableBurst.remove(i - 1);
variableBurst.remove(i - 1);
i -= 2;
ApplicationConnection.getConsole().log(
"Removed variable from removed component: " + id);
}
}
}
private void showLoadingIndicator() {
// show initial throbber
if (loadElement == null) {
loadElement = DOM.createDiv();
DOM.setStyleAttribute(loadElement, "position", "absolute");
DOM.appendChild(view.getElement(), loadElement);
ApplicationConnection.getConsole().log("inserting load indicator");
}
DOM.setElementProperty(loadElement, "className", "i-loading-indicator");
DOM.setStyleAttribute(loadElement, "display", "block");
final int updatedX = Window.getScrollLeft() + view.getAbsoluteLeft()
+ view.getOffsetWidth()
- DOM.getElementPropertyInt(loadElement, "offsetWidth") - 5;
DOM.setStyleAttribute(loadElement, "left", updatedX + "px");
final int updatedY = Window.getScrollTop() + 6 + view.getAbsoluteTop();
DOM.setStyleAttribute(loadElement, "top", updatedY + "px");
// Initialize other timers
loadTimer2 = new Timer() {
@Override
public void run() {
DOM.setElementProperty(loadElement, "className",
"i-loading-indicator-delay");
}
};
// Second one kicks in at 1500ms from request start
loadTimer2.schedule(1200);
loadTimer3 = new Timer() {
@Override
public void run() {
DOM.setElementProperty(loadElement, "className",
"i-loading-indicator-wait");
}
};
// Third one kicks in at 5000ms from request start
loadTimer3.schedule(4700);
}
private void hideLoadingIndicator() {
if (loadTimer != null) {
loadTimer.cancel();
if (loadTimer2 != null) {
loadTimer2.cancel();
loadTimer3.cancel();
}
loadTimer = null;
}
if (loadElement != null) {
DOM.setStyleAttribute(loadElement, "display", "none");
}
}
private void handleReceivedJSONMessage(Response response) {
final Date start = new Date();
String jsonText = response.getText();
// for(;;);[realjson]
jsonText = jsonText.substring(9, jsonText.length() - 1);
JSONValue json;
try {
json = JSONParser.parse(jsonText);
} catch (final com.google.gwt.json.client.JSONException e) {
endRequest();
console.log(e.getMessage() + " - Original JSON-text:");
console.log(jsonText);
return;
}
// Handle redirect
final JSONObject redirect = (JSONObject) ((JSONObject) json)
.get("redirect");
if (redirect != null) {
final JSONString url = (JSONString) redirect.get("url");
if (url != null) {
console.log("redirecting to " + url.stringValue());
redirect(url.stringValue());
return;
}
}
// Store resources
final JSONObject resources = (JSONObject) ((JSONObject) json)
.get("resources");
for (final Iterator i = resources.keySet().iterator(); i.hasNext();) {
final String key = (String) i.next();
resourcesMap.put(key, ((JSONString) resources.get(key))
.stringValue());
}
// Store locale data
if (((JSONObject) json).containsKey("locales")) {
final JSONArray l = (JSONArray) ((JSONObject) json).get("locales");
for (int i = 0; i < l.size(); i++) {
LocaleService.addLocale((JSONObject) l.get(i));
}
}
JSONObject meta = null;
if (((JSONObject) json).containsKey("meta")) {
meta = ((JSONObject) json).get("meta").isObject();
if (meta.containsKey("repaintAll")) {
view.clear();
idToPaintable.clear();
paintableToId.clear();
if (meta.containsKey("invalidLayouts")) {
validatingLayouts = true;
zeroWidthComponents = new HashSet<Paintable>();
zeroHeightComponents = new HashSet<Paintable>();
}
}
if (meta.containsKey("timedRedirect")) {
final JSONObject timedRedirect = meta.get("timedRedirect")
.isObject();
redirectTimer = new Timer() {
@Override
public void run() {
redirect(timedRedirect.get("url").isString()
.stringValue());
}
};
sessionExpirationInterval = Integer.parseInt(timedRedirect.get(
"interval").toString());
}
}
if (redirectTimer != null) {
redirectTimer.schedule(1000 * sessionExpirationInterval);
}
// Process changes
final JSONArray changes = (JSONArray) ((JSONObject) json)
.get("changes");
Vector<Paintable> updatedWidgets = new Vector<Paintable>();
relativeSizeChanges.clear();
componentCaptionSizeChanges.clear();
for (int i = 0; i < changes.size(); i++) {
try {
final UIDL change = new UIDL((JSONArray) changes.get(i));
try {
console.dirUIDL(change);
} catch (final Exception e) {
ClientExceptionHandler.displayError(e);
// TODO: dir doesn't work in any browser although it should
// work (works in hosted mode)
// it partially did at some part but now broken.
}
final UIDL uidl = change.getChildUIDL(0);
final Paintable paintable = getPaintable(uidl.getId());
if (paintable != null) {
paintable.updateFromUIDL(uidl, this);
// paintable may have changed during render to another
// implementation, use the new one for updated widgets map
updatedWidgets.add(idToPaintable.get(uidl.getId()));
} else {
if (!uidl.getTag().equals("window")) {
ClientExceptionHandler
.displayError("Received update for "
+ uidl.getTag()
+ ", but there is no such paintable ("
+ uidl.getId() + ") rendered.");
} else {
view.updateFromUIDL(uidl, this);
}
}
} catch (final Throwable e) {
ClientExceptionHandler.displayError(e);
}
}
// Check which widgets' size has been updated
Set<Paintable> sizeUpdatedWidgets = new HashSet<Paintable>();
updatedWidgets.addAll(relativeSizeChanges);
sizeUpdatedWidgets.addAll(componentCaptionSizeChanges);
for (Paintable paintable : updatedWidgets) {
Widget widget = (Widget) paintable;
Size oldSize = componentOffsetSizes.get(widget);
Size newSize = new Size(widget.getOffsetWidth(), widget
.getOffsetHeight());
if (oldSize == null || !oldSize.equals(newSize)) {
sizeUpdatedWidgets.add(paintable);
componentOffsetSizes.put(widget, newSize);
}
}
Util.componentSizeUpdated(sizeUpdatedWidgets);
if (meta != null) {
if (meta.containsKey("appError")) {
JSONObject error = meta.get("appError").isObject();
JSONValue val = error.get("caption");
String html = "";
if (val.isString() != null) {
html += "<h1>" + val.isString().stringValue() + "</h1>";
}
val = error.get("message");
if (val.isString() != null) {
html += "<p>" + val.isString().stringValue() + "</p>";
}
val = error.get("url");
String url = null;
if (val.isString() != null) {
url = val.isString().stringValue();
}
if (html.length() != 0) {
/* 45 min */
INotification n = new INotification(1000 * 60 * 45);
n.addEventListener(new NotificationRedirect(url));
n.show(html, INotification.CENTERED_TOP,
INotification.STYLE_SYSTEM);
} else {
redirect(url);
}
applicationRunning = false;
}
if (validatingLayouts) {
getConsole().printLayoutProblems(
meta.get("invalidLayouts").isArray(), this,
zeroHeightComponents, zeroWidthComponents);
zeroHeightComponents = null;
zeroWidthComponents = null;
validatingLayouts = false;
}
}
final long prosessingTime = (new Date().getTime()) - start.getTime();
console.log(" Processing time was " + String.valueOf(prosessingTime)
+ "ms for " + jsonText.length() + " characters of JSON");
console.log("Referenced paintables: " + idToPaintable.size());
endRequest();
}
/**
* This method assures that all pending variable changes are sent to server.
* Method uses synchronized xmlhttprequest and does not return before the
* changes are sent. No UIDL updates are processed and thut UI is left in
* inconsistent state. This method should be called only when closing
* windows - normally sendPendingVariableChanges() should be used.
*/
public void sendPendingVariableChangesSync() {
pendingVariableBursts.add(pendingVariables);
Vector nextBurst = (Vector) pendingVariableBursts.firstElement();
pendingVariableBursts.remove(0);
buildAndSendVariableBurst(nextBurst, true);
}
// Redirect browser, null reloads current page
private static native void redirect(String url)
/*-{
if (url) {
$wnd.location = url;
} else {
$wnd.location = $wnd.location;
}
}-*/;
public void registerPaintable(String id, Paintable paintable) {
idToPaintable.put(id, paintable);
paintableToId.put(paintable, id);
}
public void unregisterPaintable(Paintable p) {
String id = paintableToId.get(p);
idToPaintable.remove(id);
paintableToTitle.remove(id);
paintableToId.remove(p);
if (p instanceof HasWidgets) {
unregisterChildPaintables((HasWidgets) p);
}
}
public void unregisterChildPaintables(HasWidgets container) {
final Iterator it = container.iterator();
while (it.hasNext()) {
final Widget w = (Widget) it.next();
if (w instanceof Paintable) {
unregisterPaintable((Paintable) w);
} else if (w instanceof HasWidgets) {
unregisterChildPaintables((HasWidgets) w);
}
}
}
/**
* Returns Paintable element by its id
*
* @param id
* Paintable ID
*/
public Paintable getPaintable(String id) {
return idToPaintable.get(id);
}
private void addVariableToQueue(String paintableId, String variableName,
String encodedValue, boolean immediate, char type) {
final String id = paintableId + VAR_FIELD_SEPARATOR + variableName
+ VAR_FIELD_SEPARATOR + type;
for (int i = 1; i < pendingVariables.size(); i += 2) {
if ((pendingVariables.get(i)).equals(id)) {
pendingVariables.remove(i - 1);
pendingVariables.remove(i - 1);
break;
}
}
pendingVariables.add(encodedValue);
pendingVariables.add(id);
if (immediate) {
sendPendingVariableChanges();
}
}
/**
* This method sends currently queued variable changes to server. It is
* called when immediate variable update must happen.
*
* To ensure correct order for variable changes (due servers multithreading
* or network), we always wait for active request to be handler before
* sending a new one. If there is an active request, we will put varible
* "burst" to queue that will be purged after current request is handled.
*
*/
public void sendPendingVariableChanges() {
if (applicationRunning) {
if (hasActiveRequest()) {
// skip empty queues if there are pending bursts to be sent
if (pendingVariables.size() > 0
|| pendingVariableBursts.size() == 0) {
Vector burst = (Vector) pendingVariables.clone();
pendingVariableBursts.add(burst);
pendingVariables.clear();
}
} else {
buildAndSendVariableBurst(pendingVariables, false);
}
}
}
/**
* Build the variable burst and send it to server.
*
* When sync is forced, we also force sending of all pending variable-bursts
* at the same time. This is ok as we can assume that DOM will newer be
* updated after this.
*
* @param pendingVariables
* Vector of variablechanges to send
* @param forceSync
* Should we use synchronous request?
*/
private void buildAndSendVariableBurst(Vector pendingVariables,
boolean forceSync) {
final StringBuffer req = new StringBuffer();
while (!pendingVariables.isEmpty()) {
for (int i = 0; i < pendingVariables.size(); i++) {
if (i > 0) {
if (i % 2 == 0) {
req.append(VAR_RECORD_SEPARATOR);
} else {
req.append(VAR_FIELD_SEPARATOR);
}
}
req.append(pendingVariables.get(i));
}
pendingVariables.clear();
// Append all the busts to this synchronous request
if (forceSync && !pendingVariableBursts.isEmpty()) {
pendingVariables = (Vector) pendingVariableBursts
.firstElement();
pendingVariableBursts.remove(0);
req.append(VAR_BURST_SEPARATOR);
}
}
makeUidlRequest(req.toString(), false, forceSync, false);
}
public void updateVariable(String paintableId, String variableName,
String newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate, 's');
}
public void updateVariable(String paintableId, String variableName,
int newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'i');
}
public void updateVariable(String paintableId, String variableName,
long newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'l');
}
public void updateVariable(String paintableId, String variableName,
float newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'f');
}
public void updateVariable(String paintableId, String variableName,
double newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'd');
}
public void updateVariable(String paintableId, String variableName,
boolean newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue ? "true"
: "false", immediate, 'b');
}
public void updateVariable(String paintableId, String variableName,
Object[] values, boolean immediate) {
final StringBuffer buf = new StringBuffer();
for (int i = 0; i < values.length; i++) {
if (i > 0) {
buf.append(",");
}
buf.append(values[i].toString());
}
addVariableToQueue(paintableId, variableName, buf.toString(),
immediate, 'a');
}
/**
* Update generic component features.
*
* <h2>Selecting correct implementation</h2>
*
* <p>
* The implementation of a component depends on many properties, including
* styles, component features, etc. Sometimes the user changes those
* properties after the component has been created. Calling this method in
* the beginning of your updateFromUIDL -method automatically replaces your
* component with more appropriate if the requested implementation changes.
* </p>
*
* <h2>Caption, icon, error messages and description</h2>
*
* <p>
* Component can delegate management of caption, icon, error messages and
* description to parent layout. This is optional an should be decided by
* component author
* </p>
*
* <h2>Component visibility and disabling</h2>
*
* This method will manage component visibility automatically and if
* component is an instanceof FocusWidget, also handle component disabling
* when needed.
*
* @param component
* Widget to be updated, expected to implement an instance of
* Paintable
* @param uidl
* UIDL to be painted
* @param manageCaption
* True if you want to delegate caption, icon, description and
* error message management to parent.
*
* @return Returns true iff no further painting is needed by caller
*/
public boolean updateComponent(Widget component, UIDL uidl,
boolean manageCaption) {
// If the server request that a cached instance should be used, do
// nothing
if (uidl.getBooleanAttribute("cached")) {
return true;
}
// Visibility
boolean visible = !uidl.getBooleanAttribute("invisible");
boolean wasVisible = component.isVisible();
component.setVisible(visible);
if (wasVisible != visible) {
// Changed invisibile <-> visible
if (wasVisible && manageCaption) {
// Must hide caption when component is hidden
final Container parent = Util.getLayout(component);
if (parent != null) {
parent.updateCaption((Paintable) component, uidl);
}
}
}
if (!visible) {
// component is invisible, delete old size to notify parent, if
// later make visible
componentOffsetSizes.remove(component);
return true;
}
// Switch to correct implementation if needed
if (!widgetSet.isCorrectImplementation(component, uidl)) {
final Container parent = Util.getLayout(component);
if (parent != null) {
final Widget w = (Widget) widgetSet.createWidget(uidl);
parent.replaceChildComponent(component, w);
unregisterPaintable((Paintable) component);
registerPaintable(uidl.getId(), (Paintable) w);
((Paintable) w).updateFromUIDL(uidl, this);
return true;
}
}
boolean enabled = !uidl.getBooleanAttribute("disabled");
if (component instanceof FocusWidget) {
FocusWidget fw = (FocusWidget) component;
fw.setEnabled(enabled);
if (uidl.hasAttribute("tabindex")) {
fw.setTabIndex(uidl.getIntAttribute("tabindex"));
}
}
StringBuffer styleBuf = new StringBuffer();
final String primaryName = component.getStylePrimaryName();
styleBuf.append(primaryName);
// first disabling and read-only status
if (!enabled) {
styleBuf.append(" ");
styleBuf.append("i-disabled");
}
if (uidl.getBooleanAttribute("readonly")) {
styleBuf.append(" ");
styleBuf.append("i-readonly");
}
// add additional styles as css classes, prefixed with component default
// stylename
if (uidl.hasAttribute("style")) {
final String[] styles = uidl.getStringAttribute("style").split(" ");
for (int i = 0; i < styles.length; i++) {
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append("-");
styleBuf.append(styles[i]);
styleBuf.append(" ");
styleBuf.append(styles[i]);
}
}
// add modified classname to Fields
if (uidl.hasAttribute("modified") && component instanceof Field) {
styleBuf.append(" ");
styleBuf.append(MODIFIED_CLASSNAME);
}
TooltipInfo tooltipInfo = getTitleInfo((Paintable) component);
if (uidl.hasAttribute("description")) {
tooltipInfo.setTitle(uidl.getStringAttribute("description"));
} else {
tooltipInfo.setTitle(null);
}
// add error classname to components w/ error
if (uidl.hasAttribute("error")) {
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append(ERROR_CLASSNAME_EXT);
tooltipInfo.setErrorUidl(uidl.getErrors());
} else {
tooltipInfo.setErrorUidl(null);
}
// add required style to required components
if (uidl.hasAttribute("required")) {
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append(REQUIRED_CLASSNAME_EXT);
}
// Styles + disabled & readonly
component.setStyleName(styleBuf.toString());
// Set captions
if (manageCaption) {
final Container parent = Util.getLayout(component);
if (parent != null) {
parent.updateCaption((Paintable) component, uidl);
}
}
if (usePaintableIdsInDOM) {
DOM.setElementProperty(component.getElement(), "id", uidl.getId());
}
/*
* updateComponentSize need to be after caption update so caption can be
* taken into account
*/
updateComponentSize(component, uidl);
return false;
}
private void updateComponentSize(Widget component, UIDL uidl) {
String w = uidl.hasAttribute("width") ? uidl
.getStringAttribute("width") : "";
String h = uidl.hasAttribute("height") ? uidl
.getStringAttribute("height") : "";
float relativeWidth = Util.parseRelativeSize(w);
float relativeHeight = Util.parseRelativeSize(h);
// First update maps so they are correct in the setHeight/setWidth calls
if (relativeHeight >= 0.0 || relativeWidth >= 0.0) {
// One or both is relative
FloatSize relativeSize = new FloatSize(relativeWidth,
relativeHeight);
if (componentRelativeSizes.put(component, relativeSize) == null
&& componentOffsetSizes.containsKey(component)) {
// The component has changed from absolute size to relative size
relativeSizeChanges.add((Paintable) component);
}
} else if (relativeHeight < 0.0 && relativeWidth < 0.0) {
if (componentRelativeSizes.remove(component) != null) {
// The component has changed from relative size to absolute size
relativeSizeChanges.add((Paintable) component);
}
}
// Set absolute sizes
if (relativeHeight < 0.0) {
component.setHeight(h);
}
if (relativeWidth < 0.0) {
component.setWidth(w);
}
// Set relative sizes
if (relativeHeight >= 0.0 || relativeWidth >= 0.0) {
// One or both is relative
handleComponentRelativeSize(component);
}
}
/**
* Traverses recursively child widgets until ContainerResizedListener child
* widget is found. They will delegate it further if needed.
*
* @param container
*/
private boolean runningLayout = false;
public void runDescendentsLayout(HasWidgets container) {
if (runningLayout) {
// getConsole().log(
// "Already running descendents layout. Not running again for "
// + Util.getSimpleName(container));
return;
}
runningLayout = true;
internalRunDescendentsLayout(container);
runningLayout = false;
}
/**
* This will cause re-layouting of all components. Mainly used for
* development. Published to JavaScript.
*/
public void forceLayout() {
Util.componentSizeUpdated(paintableToId.keySet());
}
private void internalRunDescendentsLayout(HasWidgets container) {
// getConsole().log(
// "runDescendentsLayout(" + Util.getSimpleName(container) + ")");
final Iterator childWidgets = container.iterator();
while (childWidgets.hasNext()) {
final Widget child = (Widget) childWidgets.next();
if (child instanceof Paintable) {
if (handleComponentRelativeSize(child)) {
/*
* Only need to propagate event if "child" has a relative
* size
*/
if (child instanceof ContainerResizedListener) {
((ContainerResizedListener) child).iLayout();
}
if (child instanceof HasWidgets) {
final HasWidgets childContainer = (HasWidgets) child;
internalRunDescendentsLayout(childContainer);
}
}
} else if (child instanceof HasWidgets) {
// propagate over non Paintable HasWidgets
internalRunDescendentsLayout((HasWidgets) child);
}
}
}
/**
* Converts relative sizes into pixel sizes.
*
* @param child
* @return true if the child has a relative size
*/
public boolean handleComponentRelativeSize(Widget child) {
final boolean debugSizes = false;
Widget widget = child;
FloatSize relativeSize = getRelativeSize(child);
if (relativeSize == null) {
return false;
}
boolean horizontalScrollBar = false;
boolean verticalScrollBar = false;
Container parent = Util.getLayout(widget);
RenderSpace renderSpace;
// Parent-less components (like sub-windows) are relative to browser
// window.
if (parent == null) {
renderSpace = new RenderSpace(Window.getClientWidth(), Window
.getClientHeight());
} else {
renderSpace = parent.getAllocatedSpace(widget);
}
if (relativeSize.getHeight() >= 0) {
if (renderSpace != null) {
if (renderSpace.getScrollbarSize() > 0) {
if (relativeSize.getWidth() > 100) {
horizontalScrollBar = true;
} else if (relativeSize.getWidth() < 0
&& renderSpace.getWidth() > 0) {
int offsetWidth = widget.getOffsetWidth();
int width = renderSpace.getWidth();
if (offsetWidth > width) {
horizontalScrollBar = true;
}
}
}
int height = renderSpace.getHeight();
if (horizontalScrollBar) {
height -= renderSpace.getScrollbarSize();
}
if (validatingLayouts && height <= 0) {
zeroHeightComponents.add((Paintable) child);
}
height = (int) (height * relativeSize.getHeight() / 100.0);
if (height < 0) {
height = 0;
}
if (debugSizes) {
getConsole()
.log(
"Widget "
+ Util.getSimpleName(widget)
+ "/"
+ widget.hashCode()
+ " relative height "
+ relativeSize.getHeight()
+ "% of "
+ renderSpace.getHeight()
+ "px (reported by "
+ Util.getSimpleName(parent)
+ "/"
+ (parent == null ? "?" : parent
.hashCode()) + ") : "
+ height + "px");
}
widget.setHeight(height + "px");
} else {
widget.setHeight(relativeSize.getHeight() + "%");
ApplicationConnection.getConsole().error(
Util.getLayout(widget).getClass().getName()
+ " did not produce allocatedSpace for "
+ widget.getClass().getName());
}
}
if (relativeSize.getWidth() >= 0) {
if (renderSpace != null) {
int width = renderSpace.getWidth();
if (renderSpace.getScrollbarSize() > 0) {
if (relativeSize.getHeight() > 100) {
verticalScrollBar = true;
} else if (relativeSize.getHeight() < 0
&& renderSpace.getHeight() > 0
&& widget.getOffsetHeight() > renderSpace
.getHeight()) {
verticalScrollBar = true;
}
}
if (verticalScrollBar) {
width -= renderSpace.getScrollbarSize();
}
if (validatingLayouts && width <= 0) {
zeroWidthComponents.add((Paintable) child);
}
width = (int) (width * relativeSize.getWidth() / 100.0);
if (width < 0) {
width = 0;
}
if (debugSizes) {
getConsole()
.log(
"Widget "
+ Util.getSimpleName(widget)
+ "/"
+ widget.hashCode()
+ " relative width "
+ relativeSize.getWidth()
+ "% of "
+ renderSpace.getWidth()
+ "px (reported by "
+ Util.getSimpleName(parent)
+ "/"
+ (parent == null ? "?" : parent
.hashCode()) + ") : "
+ width + "px");
}
widget.setWidth(width + "px");
} else {
widget.setWidth(relativeSize.getWidth() + "%");
ApplicationConnection.getConsole().error(
Util.getLayout(widget).getClass().getName()
+ " did not produce allocatedSpace for "
+ widget.getClass().getName());
}
}
return true;
}
public FloatSize getRelativeSize(Widget widget) {
return componentRelativeSizes.get(widget);
}
/**
* Get either existing or new Paintable for given UIDL.
*
* If corresponding Paintable has been previously painted, return it.
* Otherwise create and register a new Paintable from UIDL. Caller must
* update the returned Paintable from UIDL after it has been connected to
* parent.
*
* @param uidl
* UIDL to create Paintable from.
* @return Either existing or new Paintable corresponding to UIDL.
*/
public Paintable getPaintable(UIDL uidl) {
final String id = uidl.getId();
Paintable w = getPaintable(id);
if (w != null) {
return w;
}
w = widgetSet.createWidget(uidl);
registerPaintable(id, w);
return w;
}
public String getResource(String name) {
return (String) resourcesMap.get(name);
}
/**
* Singleton method to get instance of app's context menu.
*
* @return IContextMenu object
*/
public IContextMenu getContextMenu() {
if (contextMenu == null) {
contextMenu = new IContextMenu();
if (usePaintableIdsInDOM) {
DOM.setElementProperty(contextMenu.getElement(), "id",
"PID_TOOLKIT_CM");
}
}
return contextMenu;
}
/**
* Translates custom protocols in UIRL URI's to be recognizable by browser.
* All uri's from UIDL should be routed via this method before giving them
* to browser due URI's in UIDL may contain custom protocols like theme://.
*
* @param toolkitUri
* toolkit URI from uidl
* @return translated URI ready for browser
*/
public String translateToolkitUri(String toolkitUri) {
if (toolkitUri == null) {
return null;
}
if (toolkitUri.startsWith("theme://")) {
final String themeUri = configuration.getThemeUri();
if (themeUri == null) {
console
.error("Theme not set: ThemeResource will not be found. ("
+ toolkitUri + ")");
}
toolkitUri = themeUri + toolkitUri.substring(7);
}
return toolkitUri;
}
public String getThemeUri() {
return configuration.getThemeUri();
}
/**
* Listens for Notification hide event, and redirects. Used for system
* messages, such as session expired.
*
*/
private class NotificationRedirect implements INotification.EventListener {
String url;
NotificationRedirect(String url) {
this.url = url;
}
public void notificationHidden(HideEvent event) {
redirect(url);
}
}
/* Extended title handling */
/**
* Data showed in tooltips are stored centrilized as it may be needed in
* varios place: caption, layouts, and in owner components themselves.
*
* Updating TooltipInfo is done in updateComponent method.
*
*/
public TooltipInfo getTitleInfo(Paintable titleOwner) {
TooltipInfo info = paintableToTitle.get(titleOwner);
if (info == null) {
info = new TooltipInfo();
paintableToTitle.put(titleOwner, info);
}
return info;
}
private final ITooltip tooltip = new ITooltip(this);
/**
* Component may want to delegate Tooltip handling to client. Layouts add
* Tooltip (description, errors) to caption, but some components may want
* them to appear one other elements too.
*
* Events wanted by this handler are same as in Tooltip.TOOLTIP_EVENTS
*
* @param event
* @param owner
*/
public void handleTooltipEvent(Event event, Paintable owner) {
tooltip.handleTooltipEvent(event, owner);
}
/**
* Adds PNG-fix conditionally (only for IE6) to the specified IMG -element.
*
* @param el
* the IMG element to fix
*/
public void addPngFix(Element el) {
BrowserInfo b = BrowserInfo.get();
if (b.isIE6()) {
Util.addPngFix(el, getThemeUri()
+ "/../default/common/img/blank.gif");
}
}
/*
* Helper to run layout functions triggered by child components with a
* decent interval.
*/
private final Timer layoutTimer = new Timer() {
private boolean isPending = false;
@Override
public void schedule(int delayMillis) {
if (!isPending) {
super.schedule(delayMillis);
isPending = true;
}
}
@Override
public void run() {
getConsole().log(
"Running re-layout of " + view.getClass().getName());
runDescendentsLayout(view);
isPending = false;
}
};
/**
* Components can call this function to run all layout functions. This is
* usually done, when component knows that its size has changed.
*/
public void requestLayoutPhase() {
layoutTimer.schedule(500);
}
private String windowName = null;
/**
* Reset the name of the current browser-window. This should reflect the
* window-name used in the server, but might be different from the
* window-object target-name on client.
*
* @param stringAttribute
* New name for the window.
*/
public void setWindowName(String newName) {
windowName = newName;
}
public void captionSizeUpdated(Paintable component) {
componentCaptionSizeChanges.add(component);
}
public void analyzeLayouts() {
makeUidlRequest("", true, false, true);
}
}
| src/com/itmill/toolkit/terminal/gwt/client/ApplicationConnection.java | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowCloseListener;
import com.google.gwt.user.client.impl.HTTPRequestImpl;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.RenderInformation.FloatSize;
import com.itmill.toolkit.terminal.gwt.client.RenderInformation.Size;
import com.itmill.toolkit.terminal.gwt.client.ui.Field;
import com.itmill.toolkit.terminal.gwt.client.ui.IContextMenu;
import com.itmill.toolkit.terminal.gwt.client.ui.INotification;
import com.itmill.toolkit.terminal.gwt.client.ui.IView;
import com.itmill.toolkit.terminal.gwt.client.ui.INotification.HideEvent;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class ApplicationConnection {
private static final String MODIFIED_CLASSNAME = "i-modified";
private static final String REQUIRED_CLASSNAME_EXT = "-required";
private static final String ERROR_CLASSNAME_EXT = "-error";
public static final String VAR_RECORD_SEPARATOR = "\u001e";
public static final String VAR_FIELD_SEPARATOR = "\u001f";
public static final String VAR_BURST_SEPARATOR = "\u001d";
public static final String UIDL_SECURITY_HEADER = "com.itmill.seckey";
private static String uidl_security_key = "init";
private final HashMap resourcesMap = new HashMap();
private static Console console;
private static boolean testingMode;
private final Vector pendingVariables = new Vector();
private final HashMap<String, Paintable> idToPaintable = new HashMap<String, Paintable>();
private final HashMap<Paintable, String> paintableToId = new HashMap<Paintable, String>();
/** Contains ExtendedTitleInfo by paintable id */
private final HashMap<Paintable, TooltipInfo> paintableToTitle = new HashMap<Paintable, TooltipInfo>();
private final HashMap<Widget, FloatSize> componentRelativeSizes = new HashMap<Widget, FloatSize>();
private final HashMap<Widget, Size> componentOffsetSizes = new HashMap<Widget, Size>();
private final WidgetSet widgetSet;
private IContextMenu contextMenu = null;
private Timer loadTimer;
private Timer loadTimer2;
private Timer loadTimer3;
private Element loadElement;
private final IView view;
private boolean applicationRunning = false;
/**
* True if each Paintable objects id is injected to DOM. Used for Testing
* Tools.
*/
private boolean usePaintableIdsInDOM = false;
/**
* Contains reference for client wrapper given to Testing Tools.
*
* Used in JSNI functions
*
*/
@SuppressWarnings("unused")
private final JavaScriptObject ttClientWrapper = null;
private int activeRequests = 0;
/** Parameters for this application connection loaded from the web-page */
private final ApplicationConfiguration configuration;
/** List of pending variable change bursts that must be submitted in order */
private final Vector pendingVariableBursts = new Vector();
/** Timer for automatic refirect to SessionExpiredURL */
private Timer redirectTimer;
/** redirectTimer scheduling interval in seconds */
private int sessionExpirationInterval;
private ArrayList<Paintable> relativeSizeChanges = new ArrayList<Paintable>();;
private ArrayList<Paintable> componentCaptionSizeChanges = new ArrayList<Paintable>();;
private Date requestStartTime;
private boolean validatingLayouts = false;
private Set<Paintable> zeroWidthComponents = null;
private Set<Paintable> zeroHeightComponents = null;
public ApplicationConnection(WidgetSet widgetSet,
ApplicationConfiguration cnf) {
this.widgetSet = widgetSet;
configuration = cnf;
if (isDebugMode()) {
console = new IDebugConsole(this, cnf, !isQuietDebugMode());
} else {
console = new NullConsole();
}
if (checkTestingMode()) {
usePaintableIdsInDOM = true;
initializeTestingTools();
Window.addWindowCloseListener(new WindowCloseListener() {
public void onWindowClosed() {
uninitializeTestingTools();
}
public String onWindowClosing() {
return null;
}
});
}
initializeClientHooks();
view = new IView(cnf.getRootPanelId());
showLoadingIndicator();
}
/**
* Starts this application. Don't call this method directly - it's called by
* {@link ApplicationConfiguration#startNextApplication()}, which should be
* called once this application has started (first response received) or
* failed to start. This ensures that the applications are started in order,
* to avoid session-id problems.
*/
void start() {
makeUidlRequest("", true, false, false);
}
/**
* Method to check if application is in testing mode. Can be used after
* application init.
*
* @return true if in testing mode
*/
public static boolean isTestingMode() {
return testingMode;
}
/**
* Check is application is run in testing mode.
*
* @return true if in testing mode
*/
private native static boolean checkTestingMode()
/*-{
try {
@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::testingMode = $wnd.top.itmill && $wnd.top.itmill.registerToTT ? true : false;
return @com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::testingMode;
} catch(e) {
// if run in iframe SOP may cause exception, return false then
return false;
}
}-*/;
private native void initializeTestingTools()
/*-{
var ap = this;
var client = {};
client.isActive = function() {
return [email protected]::hasActiveRequest()();
}
var vi = [email protected]::getVersionInfo()();
if (vi) {
client.getVersionInfo = function() {
return vi;
}
}
$wnd.top.itmill.registerToTT(client);
this.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::ttClientWrapper = client;
}-*/;
/**
* Helper for tt initialization
*/
@SuppressWarnings("unused")
private JavaScriptObject getVersionInfo() {
return configuration.getVersionInfoJSObject();
}
private native void uninitializeTestingTools()
/*-{
$wnd.top.itmill.unregisterFromTT(this.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::ttClientWrapper);
}-*/;
/**
* Publishes a JavaScript API for mash-up applications.
* <ul>
* <li><code>itmill.forceSync()</code> sends pending variable changes, in
* effect synchronizing the server and client state. This is done for all
* applications on host page.</li>
* </ul>
*
* TODO make this multi-app aware
*/
private native void initializeClientHooks()
/*-{
var app = this;
var oldSync;
if($wnd.itmill.forceSync) {
oldSync = $wnd.itmill.forceSync;
}
$wnd.itmill.forceSync = function() {
if(oldSync) {
oldSync();
}
app.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::sendPendingVariableChanges()();
}
var oldForceLayout;
if($wnd.itmill.forceLayout) {
oldForceLayout = $wnd.itmill.forceLayout;
}
$wnd.itmill.forceLayout = function() {
if(oldForceLayout) {
oldForceLayout();
}
app.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::forceLayout()();
}
}-*/;
public static Console getConsole() {
return console;
}
private native static boolean isDebugMode()
/*-{
if($wnd.itmill.debug) {
var parameters = $wnd.location.search;
var re = /debug[^\/]*$/;
return re.test(parameters);
} else {
return false;
}
}-*/;
private native static boolean isQuietDebugMode()
/*-{
var uri = $wnd.location;
var re = /debug=q[^\/]*$/;
return re.test(uri);
}-*/;
public String getAppUri() {
return configuration.getApplicationUri();
};
public boolean hasActiveRequest() {
return (activeRequests > 0);
}
private void makeUidlRequest(String requestData, boolean repaintAll,
boolean forceSync, boolean analyzeLayouts) {
startRequest();
// Security: double cookie submission pattern
requestData = uidl_security_key + VAR_BURST_SEPARATOR + requestData;
console.log("Making UIDL Request with params: " + requestData);
String uri = getAppUri() + "UIDL" + configuration.getPathInfo();
if (repaintAll) {
uri += "?repaintAll=1";
if (analyzeLayouts) {
uri += "&analyzeLayouts=1";
}
}
if (windowName != null && windowName.length() > 0) {
uri += (repaintAll ? "&" : "?") + "windowName=" + windowName;
}
if (!forceSync) {
final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
uri);
rb.setHeader("Content-Type", "text/plain;charset=utf-8");
try {
rb.sendRequest(requestData, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// TODO Better reporting to user
console.error("Got error");
endRequest();
if (!applicationRunning) {
// start failed, let's try to start the next app
ApplicationConfiguration.startNextApplication();
}
}
public void onResponseReceived(Request request,
Response response) {
if ("init".equals(uidl_security_key)) {
// Read security key
String key = response
.getHeader(UIDL_SECURITY_HEADER);
if (null != key) {
uidl_security_key = key;
}
}
console.log("Server visit took "
+ String.valueOf((new Date()).getTime()
- requestStartTime.getTime()) + "ms");
if (applicationRunning) {
handleReceivedJSONMessage(response);
} else {
applicationRunning = true;
handleWhenCSSLoaded(response);
ApplicationConfiguration.startNextApplication();
}
}
int cssWaits = 0;
static final int MAX_CSS_WAITS = 20;
private void handleWhenCSSLoaded(final Response response) {
int heightOfLoadElement = DOM.getElementPropertyInt(
loadElement, "offsetHeight");
if (heightOfLoadElement == 0
&& cssWaits < MAX_CSS_WAITS) {
(new Timer() {
@Override
public void run() {
handleWhenCSSLoaded(response);
}
}).schedule(50);
console
.log("Assuming CSS loading is not complete, "
+ "postponing render phase. "
+ "(.i-loading-indicator height == 0)");
cssWaits++;
} else {
handleReceivedJSONMessage(response);
if (cssWaits >= MAX_CSS_WAITS) {
console
.error("CSS files may have not loaded properly.");
}
}
}
});
} catch (final RequestException e) {
ClientExceptionHandler.displayError(e);
endRequest();
}
} else {
// Synchronized call, discarded response
syncSendForce(((HTTPRequestImpl) GWT.create(HTTPRequestImpl.class))
.createXmlHTTPRequest(), uri, requestData);
}
}
private native void syncSendForce(JavaScriptObject xmlHttpRequest,
String uri, String requestData)
/*-{
try {
xmlHttpRequest.open("POST", uri, false);
xmlHttpRequest.setRequestHeader("Content-Type", "text/plain;charset=utf-8");
xmlHttpRequest.send(requestData);
} catch (e) {
// No errors are managed as this is synchronous forceful send that can just fail
}
}-*/;
private void startRequest() {
activeRequests++;
requestStartTime = new Date();
// show initial throbber
if (loadTimer == null) {
loadTimer = new Timer() {
@Override
public void run() {
showLoadingIndicator();
}
};
// First one kicks in at 300ms
}
loadTimer.schedule(300);
}
private void endRequest() {
checkForPendingVariableBursts();
activeRequests--;
// deferring to avoid flickering
DeferredCommand.addCommand(new Command() {
public void execute() {
if (activeRequests == 0) {
hideLoadingIndicator();
}
}
});
}
/**
* This method is called after applying uidl change set to application.
*
* It will clean current and queued variable change sets. And send next
* change set if it exists.
*/
private void checkForPendingVariableBursts() {
cleanVariableBurst(pendingVariables);
if (pendingVariableBursts.size() > 0) {
for (Iterator iterator = pendingVariableBursts.iterator(); iterator
.hasNext();) {
cleanVariableBurst((Vector) iterator.next());
}
Vector nextBurst = (Vector) pendingVariableBursts.firstElement();
pendingVariableBursts.remove(0);
buildAndSendVariableBurst(nextBurst, false);
}
}
/**
* Cleans given queue of variable changes of such changes that came from
* components that do not exist anymore.
*
* @param variableBurst
*/
private void cleanVariableBurst(Vector variableBurst) {
for (int i = 1; i < variableBurst.size(); i += 2) {
String id = (String) variableBurst.get(i);
id = id.substring(0, id.indexOf(VAR_FIELD_SEPARATOR));
if (!idToPaintable.containsKey(id)) {
// variable owner does not exist anymore
variableBurst.remove(i - 1);
variableBurst.remove(i - 1);
i -= 2;
ApplicationConnection.getConsole().log(
"Removed variable from removed component: " + id);
}
}
}
private void showLoadingIndicator() {
// show initial throbber
if (loadElement == null) {
loadElement = DOM.createDiv();
DOM.setStyleAttribute(loadElement, "position", "absolute");
DOM.appendChild(view.getElement(), loadElement);
ApplicationConnection.getConsole().log("inserting load indicator");
}
DOM.setElementProperty(loadElement, "className", "i-loading-indicator");
DOM.setStyleAttribute(loadElement, "display", "block");
final int updatedX = Window.getScrollLeft() + view.getAbsoluteLeft()
+ view.getOffsetWidth()
- DOM.getElementPropertyInt(loadElement, "offsetWidth") - 5;
DOM.setStyleAttribute(loadElement, "left", updatedX + "px");
final int updatedY = Window.getScrollTop() + 6 + view.getAbsoluteTop();
DOM.setStyleAttribute(loadElement, "top", updatedY + "px");
// Initialize other timers
loadTimer2 = new Timer() {
@Override
public void run() {
DOM.setElementProperty(loadElement, "className",
"i-loading-indicator-delay");
}
};
// Second one kicks in at 1500ms from request start
loadTimer2.schedule(1200);
loadTimer3 = new Timer() {
@Override
public void run() {
DOM.setElementProperty(loadElement, "className",
"i-loading-indicator-wait");
}
};
// Third one kicks in at 5000ms from request start
loadTimer3.schedule(4700);
}
private void hideLoadingIndicator() {
if (loadTimer != null) {
loadTimer.cancel();
if (loadTimer2 != null) {
loadTimer2.cancel();
loadTimer3.cancel();
}
loadTimer = null;
}
if (loadElement != null) {
DOM.setStyleAttribute(loadElement, "display", "none");
}
}
private void handleReceivedJSONMessage(Response response) {
final Date start = new Date();
String jsonText = response.getText();
// for(;;);[realjson]
jsonText = jsonText.substring(9, jsonText.length() - 1);
JSONValue json;
try {
json = JSONParser.parse(jsonText);
} catch (final com.google.gwt.json.client.JSONException e) {
endRequest();
console.log(e.getMessage() + " - Original JSON-text:");
console.log(jsonText);
return;
}
// Handle redirect
final JSONObject redirect = (JSONObject) ((JSONObject) json)
.get("redirect");
if (redirect != null) {
final JSONString url = (JSONString) redirect.get("url");
if (url != null) {
console.log("redirecting to " + url.stringValue());
redirect(url.stringValue());
return;
}
}
// Store resources
final JSONObject resources = (JSONObject) ((JSONObject) json)
.get("resources");
for (final Iterator i = resources.keySet().iterator(); i.hasNext();) {
final String key = (String) i.next();
resourcesMap.put(key, ((JSONString) resources.get(key))
.stringValue());
}
// Store locale data
if (((JSONObject) json).containsKey("locales")) {
final JSONArray l = (JSONArray) ((JSONObject) json).get("locales");
for (int i = 0; i < l.size(); i++) {
LocaleService.addLocale((JSONObject) l.get(i));
}
}
JSONObject meta = null;
if (((JSONObject) json).containsKey("meta")) {
meta = ((JSONObject) json).get("meta").isObject();
if (meta.containsKey("repaintAll")) {
view.clear();
idToPaintable.clear();
paintableToId.clear();
if (meta.containsKey("invalidLayouts")) {
validatingLayouts = true;
zeroWidthComponents = new HashSet<Paintable>();
zeroHeightComponents = new HashSet<Paintable>();
}
}
if (meta.containsKey("timedRedirect")) {
final JSONObject timedRedirect = meta.get("timedRedirect")
.isObject();
redirectTimer = new Timer() {
@Override
public void run() {
redirect(timedRedirect.get("url").isString()
.stringValue());
}
};
sessionExpirationInterval = Integer.parseInt(timedRedirect.get(
"interval").toString());
}
}
if (redirectTimer != null) {
redirectTimer.schedule(1000 * sessionExpirationInterval);
}
// Process changes
final JSONArray changes = (JSONArray) ((JSONObject) json)
.get("changes");
Vector<Paintable> updatedWidgets = new Vector<Paintable>();
relativeSizeChanges.clear();
componentCaptionSizeChanges.clear();
for (int i = 0; i < changes.size(); i++) {
try {
final UIDL change = new UIDL((JSONArray) changes.get(i));
try {
console.dirUIDL(change);
} catch (final Exception e) {
ClientExceptionHandler.displayError(e);
// TODO: dir doesn't work in any browser although it should
// work (works in hosted mode)
// it partially did at some part but now broken.
}
final UIDL uidl = change.getChildUIDL(0);
final Paintable paintable = getPaintable(uidl.getId());
if (paintable != null) {
paintable.updateFromUIDL(uidl, this);
// paintable may have changed during render to another
// implementation, use the new one for updated widgets map
updatedWidgets.add(idToPaintable.get(uidl.getId()));
} else {
if (!uidl.getTag().equals("window")) {
ClientExceptionHandler
.displayError("Received update for "
+ uidl.getTag()
+ ", but there is no such paintable ("
+ uidl.getId() + ") rendered.");
} else {
view.updateFromUIDL(uidl, this);
}
}
} catch (final Throwable e) {
ClientExceptionHandler.displayError(e);
}
}
// Check which widgets' size has been updated
Set<Paintable> sizeUpdatedWidgets = new HashSet<Paintable>();
updatedWidgets.addAll(relativeSizeChanges);
sizeUpdatedWidgets.addAll(componentCaptionSizeChanges);
for (Paintable paintable : updatedWidgets) {
Widget widget = (Widget) paintable;
Size oldSize = componentOffsetSizes.get(widget);
Size newSize = new Size(widget.getOffsetWidth(), widget
.getOffsetHeight());
if (oldSize == null || !oldSize.equals(newSize)) {
sizeUpdatedWidgets.add(paintable);
componentOffsetSizes.put(widget, newSize);
}
}
Util.componentSizeUpdated(sizeUpdatedWidgets);
if (meta != null) {
if (meta.containsKey("appError")) {
JSONObject error = meta.get("appError").isObject();
JSONValue val = error.get("caption");
String html = "";
if (val.isString() != null) {
html += "<h1>" + val.isString().stringValue() + "</h1>";
}
val = error.get("message");
if (val.isString() != null) {
html += "<p>" + val.isString().stringValue() + "</p>";
}
val = error.get("url");
String url = null;
if (val.isString() != null) {
url = val.isString().stringValue();
}
if (html.length() != 0) {
/* 45 min */
INotification n = new INotification(1000 * 60 * 45);
n.addEventListener(new NotificationRedirect(url));
n.show(html, INotification.CENTERED_TOP,
INotification.STYLE_SYSTEM);
} else {
redirect(url);
}
applicationRunning = false;
}
if (validatingLayouts) {
getConsole().printLayoutProblems(
meta.get("invalidLayouts").isArray(), this,
zeroHeightComponents, zeroWidthComponents);
zeroHeightComponents = null;
zeroWidthComponents = null;
validatingLayouts = false;
}
}
final long prosessingTime = (new Date().getTime()) - start.getTime();
console.log(" Processing time was " + String.valueOf(prosessingTime)
+ "ms for " + jsonText.length() + " characters of JSON");
console.log("Referenced paintables: " + idToPaintable.size());
endRequest();
}
/**
* This method assures that all pending variable changes are sent to server.
* Method uses synchronized xmlhttprequest and does not return before the
* changes are sent. No UIDL updates are processed and thut UI is left in
* inconsistent state. This method should be called only when closing
* windows - normally sendPendingVariableChanges() should be used.
*/
public void sendPendingVariableChangesSync() {
pendingVariableBursts.add(pendingVariables);
Vector nextBurst = (Vector) pendingVariableBursts.firstElement();
pendingVariableBursts.remove(0);
buildAndSendVariableBurst(nextBurst, true);
}
// Redirect browser, null reloads current page
private static native void redirect(String url)
/*-{
if (url) {
$wnd.location = url;
} else {
$wnd.location = $wnd.location;
}
}-*/;
public void registerPaintable(String id, Paintable paintable) {
idToPaintable.put(id, paintable);
paintableToId.put(paintable, id);
}
public void unregisterPaintable(Paintable p) {
String id = paintableToId.get(p);
idToPaintable.remove(id);
paintableToTitle.remove(id);
paintableToId.remove(p);
if (p instanceof HasWidgets) {
unregisterChildPaintables((HasWidgets) p);
}
}
public void unregisterChildPaintables(HasWidgets container) {
final Iterator it = container.iterator();
while (it.hasNext()) {
final Widget w = (Widget) it.next();
if (w instanceof Paintable) {
unregisterPaintable((Paintable) w);
} else if (w instanceof HasWidgets) {
unregisterChildPaintables((HasWidgets) w);
}
}
}
/**
* Returns Paintable element by its id
*
* @param id
* Paintable ID
*/
public Paintable getPaintable(String id) {
return idToPaintable.get(id);
}
private void addVariableToQueue(String paintableId, String variableName,
String encodedValue, boolean immediate, char type) {
final String id = paintableId + VAR_FIELD_SEPARATOR + variableName
+ VAR_FIELD_SEPARATOR + type;
for (int i = 1; i < pendingVariables.size(); i += 2) {
if ((pendingVariables.get(i)).equals(id)) {
pendingVariables.remove(i - 1);
pendingVariables.remove(i - 1);
break;
}
}
pendingVariables.add(encodedValue);
pendingVariables.add(id);
if (immediate) {
sendPendingVariableChanges();
}
}
/**
* This method sends currently queued variable changes to server. It is
* called when immediate variable update must happen.
*
* To ensure correct order for variable changes (due servers multithreading
* or network), we always wait for active request to be handler before
* sending a new one. If there is an active request, we will put varible
* "burst" to queue that will be purged after current request is handled.
*
*/
public void sendPendingVariableChanges() {
if (applicationRunning) {
if (hasActiveRequest()) {
// skip empty queues if there are pending bursts to be sent
if (pendingVariables.size() > 0
|| pendingVariableBursts.size() == 0) {
Vector burst = (Vector) pendingVariables.clone();
pendingVariableBursts.add(burst);
pendingVariables.clear();
}
} else {
buildAndSendVariableBurst(pendingVariables, false);
}
}
}
/**
* Build the variable burst and send it to server.
*
* When sync is forced, we also force sending of all pending variable-bursts
* at the same time. This is ok as we can assume that DOM will newer be
* updated after this.
*
* @param pendingVariables
* Vector of variablechanges to send
* @param forceSync
* Should we use synchronous request?
*/
private void buildAndSendVariableBurst(Vector pendingVariables,
boolean forceSync) {
final StringBuffer req = new StringBuffer();
while (!pendingVariables.isEmpty()) {
for (int i = 0; i < pendingVariables.size(); i++) {
if (i > 0) {
if (i % 2 == 0) {
req.append(VAR_RECORD_SEPARATOR);
} else {
req.append(VAR_FIELD_SEPARATOR);
}
}
req.append(pendingVariables.get(i));
}
pendingVariables.clear();
// Append all the busts to this synchronous request
if (forceSync && !pendingVariableBursts.isEmpty()) {
pendingVariables = (Vector) pendingVariableBursts
.firstElement();
pendingVariableBursts.remove(0);
req.append(VAR_BURST_SEPARATOR);
}
}
makeUidlRequest(req.toString(), false, forceSync, false);
}
public void updateVariable(String paintableId, String variableName,
String newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue, immediate, 's');
}
public void updateVariable(String paintableId, String variableName,
int newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'i');
}
public void updateVariable(String paintableId, String variableName,
long newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'l');
}
public void updateVariable(String paintableId, String variableName,
float newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'f');
}
public void updateVariable(String paintableId, String variableName,
double newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
'd');
}
public void updateVariable(String paintableId, String variableName,
boolean newValue, boolean immediate) {
addVariableToQueue(paintableId, variableName, newValue ? "true"
: "false", immediate, 'b');
}
public void updateVariable(String paintableId, String variableName,
Object[] values, boolean immediate) {
final StringBuffer buf = new StringBuffer();
for (int i = 0; i < values.length; i++) {
if (i > 0) {
buf.append(",");
}
buf.append(values[i].toString());
}
addVariableToQueue(paintableId, variableName, buf.toString(),
immediate, 'a');
}
/**
* Update generic component features.
*
* <h2>Selecting correct implementation</h2>
*
* <p>
* The implementation of a component depends on many properties, including
* styles, component features, etc. Sometimes the user changes those
* properties after the component has been created. Calling this method in
* the beginning of your updateFromUIDL -method automatically replaces your
* component with more appropriate if the requested implementation changes.
* </p>
*
* <h2>Caption, icon, error messages and description</h2>
*
* <p>
* Component can delegate management of caption, icon, error messages and
* description to parent layout. This is optional an should be decided by
* component author
* </p>
*
* <h2>Component visibility and disabling</h2>
*
* This method will manage component visibility automatically and if
* component is an instanceof FocusWidget, also handle component disabling
* when needed.
*
* @param component
* Widget to be updated, expected to implement an instance of
* Paintable
* @param uidl
* UIDL to be painted
* @param manageCaption
* True if you want to delegate caption, icon, description and
* error message management to parent.
*
* @return Returns true iff no further painting is needed by caller
*/
public boolean updateComponent(Widget component, UIDL uidl,
boolean manageCaption) {
// If the server request that a cached instance should be used, do
// nothing
if (uidl.getBooleanAttribute("cached")) {
return true;
}
// Visibility
boolean visible = !uidl.getBooleanAttribute("invisible");
boolean wasVisible = component.isVisible();
component.setVisible(visible);
if (wasVisible != visible) {
// Changed invisibile <-> visible
if (wasVisible && manageCaption) {
// Must hide caption when component is hidden
final Container parent = Util.getLayout(component);
if (parent != null) {
parent.updateCaption((Paintable) component, uidl);
}
}
}
if (!visible) {
// component is invisible, delete old size to notify parent, if
// later make visible
componentOffsetSizes.remove(component);
return true;
}
// Switch to correct implementation if needed
if (!widgetSet.isCorrectImplementation(component, uidl)) {
final Container parent = Util.getLayout(component);
if (parent != null) {
final Widget w = (Widget) widgetSet.createWidget(uidl);
parent.replaceChildComponent(component, w);
unregisterPaintable((Paintable) component);
registerPaintable(uidl.getId(), (Paintable) w);
((Paintable) w).updateFromUIDL(uidl, this);
return true;
}
}
boolean enabled = !uidl.getBooleanAttribute("disabled");
if (component instanceof FocusWidget) {
FocusWidget fw = (FocusWidget) component;
fw.setEnabled(enabled);
if (uidl.hasAttribute("tabindex")) {
fw.setTabIndex(uidl.getIntAttribute("tabindex"));
}
}
StringBuffer styleBuf = new StringBuffer();
final String primaryName = component.getStylePrimaryName();
styleBuf.append(primaryName);
// first disabling and read-only status
if (!enabled) {
styleBuf.append(" ");
styleBuf.append("i-disabled");
}
if (uidl.getBooleanAttribute("readonly")) {
styleBuf.append(" ");
styleBuf.append("i-readonly");
}
// add additional styles as css classes, prefixed with component default
// stylename
if (uidl.hasAttribute("style")) {
final String[] styles = uidl.getStringAttribute("style").split(" ");
for (int i = 0; i < styles.length; i++) {
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append("-");
styleBuf.append(styles[i]);
styleBuf.append(" ");
styleBuf.append(styles[i]);
}
}
// add modified classname to Fields
if (uidl.hasAttribute("modified") && component instanceof Field) {
styleBuf.append(" ");
styleBuf.append(MODIFIED_CLASSNAME);
}
TooltipInfo tooltipInfo = getTitleInfo((Paintable) component);
if (uidl.hasAttribute("description")) {
tooltipInfo.setTitle(uidl.getStringAttribute("description"));
} else {
tooltipInfo.setTitle(null);
}
// add error classname to components w/ error
if (uidl.hasAttribute("error")) {
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append(ERROR_CLASSNAME_EXT);
tooltipInfo.setErrorUidl(uidl.getErrors());
} else {
tooltipInfo.setErrorUidl(null);
}
// add required style to required components
if (uidl.hasAttribute("required")) {
styleBuf.append(" ");
styleBuf.append(primaryName);
styleBuf.append(REQUIRED_CLASSNAME_EXT);
}
// Styles + disabled & readonly
component.setStyleName(styleBuf.toString());
// Set captions
if (manageCaption) {
final Container parent = Util.getLayout(component);
if (parent != null) {
parent.updateCaption((Paintable) component, uidl);
}
}
if (usePaintableIdsInDOM) {
DOM.setElementProperty(component.getElement(), "id", uidl.getId());
}
/*
* updateComponentSize need to be after caption update so caption can be
* taken into account
*/
updateComponentSize(component, uidl);
return false;
}
private void updateComponentSize(Widget component, UIDL uidl) {
String w = uidl.hasAttribute("width") ? uidl
.getStringAttribute("width") : "";
String h = uidl.hasAttribute("height") ? uidl
.getStringAttribute("height") : "";
float relativeWidth = Util.parseRelativeSize(w);
float relativeHeight = Util.parseRelativeSize(h);
// First update maps so they are correct in the setHeight/setWidth calls
if (relativeHeight >= 0.0 || relativeWidth >= 0.0) {
// One or both is relative
FloatSize relativeSize = new FloatSize(relativeWidth,
relativeHeight);
if (componentRelativeSizes.put(component, relativeSize) == null
&& componentOffsetSizes.containsKey(component)) {
// The component has changed from absolute size to relative size
relativeSizeChanges.add((Paintable) component);
}
} else if (relativeHeight < 0.0 && relativeWidth < 0.0) {
if (componentRelativeSizes.remove(component) != null) {
// The component has changed from relative size to absolute size
relativeSizeChanges.add((Paintable) component);
}
}
// Set absolute sizes
if (relativeHeight < 0.0) {
component.setHeight(h);
}
if (relativeWidth < 0.0) {
component.setWidth(w);
}
// Set relative sizes
if (relativeHeight >= 0.0 || relativeWidth >= 0.0) {
// One or both is relative
handleComponentRelativeSize(component);
}
}
/**
* Traverses recursively child widgets until ContainerResizedListener child
* widget is found. They will delegate it further if needed.
*
* @param container
*/
private boolean runningLayout = false;
public void runDescendentsLayout(HasWidgets container) {
if (runningLayout) {
// getConsole().log(
// "Already running descendents layout. Not running again for "
// + Util.getSimpleName(container));
return;
}
runningLayout = true;
internalRunDescendentsLayout(container);
runningLayout = false;
}
/**
* This will cause re-layouting of all components. Mainly used for
* development. Published to JavaScript.
*/
public void forceLayout() {
Util.componentSizeUpdated(paintableToId.keySet());
}
private void internalRunDescendentsLayout(HasWidgets container) {
// getConsole().log(
// "runDescendentsLayout(" + Util.getSimpleName(container) + ")");
final Iterator childWidgets = container.iterator();
while (childWidgets.hasNext()) {
final Widget child = (Widget) childWidgets.next();
if (child instanceof Paintable) {
if (handleComponentRelativeSize(child)) {
/*
* Only need to propagate event if "child" has a relative
* size
*/
if (child instanceof ContainerResizedListener) {
((ContainerResizedListener) child).iLayout();
}
if (child instanceof HasWidgets) {
final HasWidgets childContainer = (HasWidgets) child;
internalRunDescendentsLayout(childContainer);
}
}
} else if (child instanceof HasWidgets) {
// propagate over non Paintable HasWidgets
internalRunDescendentsLayout((HasWidgets) child);
}
}
}
/**
* Converts relative sizes into pixel sizes.
*
* @param child
* @return true if the child has a relative size
*/
public boolean handleComponentRelativeSize(Widget child) {
final boolean debugSizes = false;
Widget widget = child;
FloatSize relativeSize = getRelativeSize(child);
if (relativeSize == null) {
return false;
}
boolean horizontalScrollBar = false;
boolean verticalScrollBar = false;
Container parent = Util.getLayout(widget);
RenderSpace renderSpace;
// Parent-less components (like sub-windows) are relative to browser
// window.
if (parent == null) {
renderSpace = new RenderSpace(Window.getClientWidth(), Window
.getClientHeight());
} else {
renderSpace = parent.getAllocatedSpace(widget);
}
if (relativeSize.getHeight() >= 0) {
if (renderSpace != null) {
if (renderSpace.getScrollbarSize() > 0) {
if (relativeSize.getWidth() > 100) {
horizontalScrollBar = true;
} else if (relativeSize.getWidth() < 0
&& renderSpace.getWidth() > 0) {
int offsetWidth = widget.getOffsetWidth();
int width = renderSpace.getWidth();
if (offsetWidth > width) {
horizontalScrollBar = true;
}
}
}
int height = renderSpace.getHeight();
if (horizontalScrollBar) {
height -= renderSpace.getScrollbarSize();
}
if (validatingLayouts && height <= 0) {
zeroHeightComponents.add((Paintable) child);
}
height = (int) (height * relativeSize.getHeight() / 100.0);
if (height < 0) {
height = 0;
}
if (debugSizes) {
getConsole()
.log(
"Widget "
+ Util.getSimpleName(widget)
+ "/"
+ widget.hashCode()
+ " relative height "
+ relativeSize.getHeight()
+ "% of "
+ renderSpace.getHeight()
+ "px (reported by "
+ Util.getSimpleName(parent)
+ "/"
+ (parent == null ? "?" : parent
.hashCode()) + ") : "
+ height + "px");
}
widget.setHeight(height + "px");
} else {
widget.setHeight(relativeSize.getHeight() + "%");
ApplicationConnection.getConsole().error(
Util.getLayout(widget).getClass().getName()
+ " did not produce allocatedSpace for "
+ widget.getClass().getName());
}
}
if (relativeSize.getWidth() >= 0) {
if (renderSpace != null) {
int width = renderSpace.getWidth();
if (renderSpace.getScrollbarSize() > 0) {
if (relativeSize.getHeight() > 100) {
verticalScrollBar = true;
} else if (relativeSize.getHeight() < 0
&& renderSpace.getHeight() > 0
&& widget.getOffsetHeight() > renderSpace
.getHeight()) {
verticalScrollBar = true;
}
}
if (verticalScrollBar) {
width -= renderSpace.getScrollbarSize();
}
if (validatingLayouts && width <= 0) {
zeroWidthComponents.add((Paintable) child);
}
width = (int) (width * relativeSize.getWidth() / 100.0);
if (width < 0) {
width = 0;
}
if (debugSizes) {
getConsole()
.log(
"Widget "
+ Util.getSimpleName(widget)
+ "/"
+ widget.hashCode()
+ " relative width "
+ relativeSize.getWidth()
+ "% of "
+ renderSpace.getWidth()
+ "px (reported by "
+ Util.getSimpleName(parent)
+ "/"
+ (parent == null ? "?" : parent
.hashCode()) + ") : "
+ width + "px");
}
widget.setWidth(width + "px");
} else {
widget.setWidth(relativeSize.getWidth() + "%");
ApplicationConnection.getConsole().error(
Util.getLayout(widget).getClass().getName()
+ " did not produce allocatedSpace for "
+ widget.getClass().getName());
}
}
return true;
}
public FloatSize getRelativeSize(Widget widget) {
return componentRelativeSizes.get(widget);
}
/**
* Get either existing or new Paintable for given UIDL.
*
* If corresponding Paintable has been previously painted, return it.
* Otherwise create and register a new Paintable from UIDL. Caller must
* update the returned Paintable from UIDL after it has been connected to
* parent.
*
* @param uidl
* UIDL to create Paintable from.
* @return Either existing or new Paintable corresponding to UIDL.
*/
public Paintable getPaintable(UIDL uidl) {
final String id = uidl.getId();
Paintable w = getPaintable(id);
if (w != null) {
return w;
}
w = widgetSet.createWidget(uidl);
registerPaintable(id, w);
return w;
}
public String getResource(String name) {
return (String) resourcesMap.get(name);
}
/**
* Singleton method to get instance of app's context menu.
*
* @return IContextMenu object
*/
public IContextMenu getContextMenu() {
if (contextMenu == null) {
contextMenu = new IContextMenu();
if (usePaintableIdsInDOM) {
DOM.setElementProperty(contextMenu.getElement(), "id",
"PID_TOOLKIT_CM");
}
}
return contextMenu;
}
/**
* Translates custom protocols in UIRL URI's to be recognizable by browser.
* All uri's from UIDL should be routed via this method before giving them
* to browser due URI's in UIDL may contain custom protocols like theme://.
*
* @param toolkitUri
* toolkit URI from uidl
* @return translated URI ready for browser
*/
public String translateToolkitUri(String toolkitUri) {
if (toolkitUri == null) {
return null;
}
if (toolkitUri.startsWith("theme://")) {
final String themeUri = configuration.getThemeUri();
if (themeUri == null) {
console
.error("Theme not set: ThemeResource will not be found. ("
+ toolkitUri + ")");
}
toolkitUri = themeUri + toolkitUri.substring(7);
}
return toolkitUri;
}
public String getThemeUri() {
return configuration.getThemeUri();
}
/**
* Listens for Notification hide event, and redirects. Used for system
* messages, such as session expired.
*
*/
private class NotificationRedirect implements INotification.EventListener {
String url;
NotificationRedirect(String url) {
this.url = url;
}
public void notificationHidden(HideEvent event) {
redirect(url);
}
}
/* Extended title handling */
/**
* Data showed in tooltips are stored centrilized as it may be needed in
* varios place: caption, layouts, and in owner components themselves.
*
* Updating TooltipInfo is done in updateComponent method.
*
*/
public TooltipInfo getTitleInfo(Paintable titleOwner) {
TooltipInfo info = paintableToTitle.get(titleOwner);
if (info == null) {
info = new TooltipInfo();
paintableToTitle.put(titleOwner, info);
}
return info;
}
private final ITooltip tooltip = new ITooltip(this);
/**
* Component may want to delegate Tooltip handling to client. Layouts add
* Tooltip (description, errors) to caption, but some components may want
* them to appear one other elements too.
*
* Events wanted by this handler are same as in Tooltip.TOOLTIP_EVENTS
*
* @param event
* @param owner
*/
public void handleTooltipEvent(Event event, Paintable owner) {
tooltip.handleTooltipEvent(event, owner);
}
/**
* Adds PNG-fix conditionally (only for IE6) to the specified IMG -element.
*
* @param el
* the IMG element to fix
*/
public void addPngFix(Element el) {
BrowserInfo b = BrowserInfo.get();
if (b.isIE6()) {
Util.addPngFix(el, getThemeUri()
+ "/../default/common/img/blank.gif");
}
}
/*
* Helper to run layout functions triggered by child components with a
* decent interval.
*/
private final Timer layoutTimer = new Timer() {
private boolean isPending = false;
@Override
public void schedule(int delayMillis) {
if (!isPending) {
super.schedule(delayMillis);
isPending = true;
}
}
@Override
public void run() {
getConsole().log(
"Running re-layout of " + view.getClass().getName());
runDescendentsLayout(view);
isPending = false;
}
};
/**
* Components can call this function to run all layout functions. This is
* usually done, when component knows that its size has changed.
*/
public void requestLayoutPhase() {
layoutTimer.schedule(500);
}
private String windowName = null;
/**
* Reset the name of the current browser-window. This should reflect the
* window-name used in the server, but might be different from the
* window-object target-name on client.
*
* @param stringAttribute
* New name for the window.
*/
public void setWindowName(String newName) {
windowName = newName;
}
public void captionSizeUpdated(Paintable component) {
componentCaptionSizeChanges.add(component);
}
public void analyzeLayouts() {
makeUidlRequest("", true, false, true);
}
}
| Fix for #2396 - loading indicator stays on in IE7
svn changeset:6308/svn branch:trunk
| src/com/itmill/toolkit/terminal/gwt/client/ApplicationConnection.java | Fix for #2396 - loading indicator stays on in IE7 |
|
Java | apache-2.0 | d29941f5af6536331b544cda4ec20b3b748103c2 | 0 | jruesga/rview,jruesga/rview,jruesga/rview | /*
* Copyright (C) 2016 Jorge Ruesga
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ruesga.rview.gerrit;
import android.annotation.SuppressLint;
import android.net.TrafficStats;
import android.os.Build;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
public class OkHttpHelper {
// https://github.com/square/okhttp/blob/master/okhttp-tests/src/test/java/okhttp3/DelegatingSocketFactory.java
private static class DelegatingSocketFactory extends SocketFactory {
private final javax.net.SocketFactory mDelegate;
private DelegatingSocketFactory(javax.net.SocketFactory delegate) {
this.mDelegate = delegate;
}
@Override public Socket createSocket() throws IOException {
Socket socket = mDelegate.createSocket();
return configureSocket(socket);
}
@Override public Socket createSocket(String host, int port) throws IOException {
Socket socket = mDelegate.createSocket(host, port);
return configureSocket(socket);
}
@Override public Socket createSocket(String host, int port, InetAddress localAddress,
int localPort) throws IOException {
Socket socket = mDelegate.createSocket(host, port, localAddress, localPort);
return configureSocket(socket);
}
@Override public Socket createSocket(InetAddress host, int port) throws IOException {
Socket socket = mDelegate.createSocket(host, port);
return configureSocket(socket);
}
@Override public Socket createSocket(InetAddress host, int port, InetAddress localAddress,
int localPort) throws IOException {
Socket socket = mDelegate.createSocket(host, port, localAddress, localPort);
return configureSocket(socket);
}
private Socket configureSocket(Socket socket) {
try {
TrafficStats.setThreadStatsTag(
Math.max(1, Math.min(0xFFFFFEFF, Thread.currentThread().hashCode())));
TrafficStats.tagSocket(socket);
} catch (Throwable cause) {
// Ignore for testing
}
return socket;
}
}
@SuppressLint("TrustAllX509TrustManager")
private static final X509TrustManager TRUST_ALL_CERTS = new X509TrustManager() {
@Override
public void checkClientTrusted(
X509Certificate[] x509Certificates, String authType) {
}
@Override
public void checkServerTrusted(
X509Certificate[] x509Certificates, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
};
private static SSLSocketFactory sSSLSocketFactory;
private static DelegatingSocketFactory sDelegatingSocketFactory;
public static OkHttpClient.Builder getSafeClientBuilder() {
if (sDelegatingSocketFactory == null) {
sDelegatingSocketFactory = new DelegatingSocketFactory(SocketFactory.getDefault());
}
return new OkHttpClient.Builder()
.connectionSpecs(createConnectionSpecs(ConnectionSpec.RESTRICTED_TLS, false))
.socketFactory(sDelegatingSocketFactory);
}
@SuppressLint("BadHostnameVerifier")
static OkHttpClient.Builder getUnsafeClientBuilder() {
OkHttpClient.Builder builder = getSafeClientBuilder();
try {
if (sSSLSocketFactory == null) {
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new X509TrustManager[]{TRUST_ALL_CERTS}, null);
sSSLSocketFactory = sslContext.getSocketFactory();
}
builder.connectionSpecs(createConnectionSpecs(ConnectionSpec.MODERN_TLS, true));
builder.sslSocketFactory(sSSLSocketFactory, TRUST_ALL_CERTS);
builder.hostnameVerifier((hostname, session) -> hostname != null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
// Ignore
}
return builder;
}
private static List<ConnectionSpec> createConnectionSpecs(ConnectionSpec specs,
boolean forceAllCipherSuites) {
ConnectionSpec.Builder spec = new ConnectionSpec.Builder(specs);
if (Build.VERSION.RELEASE.equals("7.0") || forceAllCipherSuites) {
// There is a bug in Android 7.0 (https://issuetracker.google.com/issues/37122132)
// that only supports the prime256v1 elliptic curve. So in just release the
// cipher requirements if we are in that case.
spec.allEnabledCipherSuites();
}
return Arrays.asList(ConnectionSpec.CLEARTEXT, spec.build());
}
}
| gerrit/src/main/java/com/ruesga/rview/gerrit/OkHttpHelper.java | /*
* Copyright (C) 2016 Jorge Ruesga
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ruesga.rview.gerrit;
import android.annotation.SuppressLint;
import android.net.TrafficStats;
import android.os.Build;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
public class OkHttpHelper {
// https://github.com/square/okhttp/blob/master/okhttp-tests/src/test/java/okhttp3/DelegatingSocketFactory.java
private static class DelegatingSocketFactory extends SocketFactory {
private final javax.net.SocketFactory mDelegate;
private DelegatingSocketFactory(javax.net.SocketFactory delegate) {
this.mDelegate = delegate;
}
@Override public Socket createSocket() throws IOException {
Socket socket = mDelegate.createSocket();
return configureSocket(socket);
}
@Override public Socket createSocket(String host, int port) throws IOException {
Socket socket = mDelegate.createSocket(host, port);
return configureSocket(socket);
}
@Override public Socket createSocket(String host, int port, InetAddress localAddress,
int localPort) throws IOException {
Socket socket = mDelegate.createSocket(host, port, localAddress, localPort);
return configureSocket(socket);
}
@Override public Socket createSocket(InetAddress host, int port) throws IOException {
Socket socket = mDelegate.createSocket(host, port);
return configureSocket(socket);
}
@Override public Socket createSocket(InetAddress host, int port, InetAddress localAddress,
int localPort) throws IOException {
Socket socket = mDelegate.createSocket(host, port, localAddress, localPort);
return configureSocket(socket);
}
private Socket configureSocket(Socket socket) {
try {
TrafficStats.setThreadStatsTag(
Math.max(1, Math.min(0xFFFFFEFF, Thread.currentThread().hashCode())));
TrafficStats.tagSocket(socket);
} catch (Throwable cause) {
// Ignore for testing
}
return socket;
}
}
@SuppressLint("TrustAllX509TrustManager")
private static final X509TrustManager TRUST_ALL_CERTS = new X509TrustManager() {
@Override
public void checkClientTrusted(
X509Certificate[] x509Certificates, String authType) {
}
@Override
public void checkServerTrusted(
X509Certificate[] x509Certificates, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
};
private static SSLSocketFactory sSSLSocketFactory;
private static DelegatingSocketFactory sDelegatingSocketFactory;
public static OkHttpClient.Builder getSafeClientBuilder() {
if (sDelegatingSocketFactory == null) {
sDelegatingSocketFactory = new DelegatingSocketFactory(SocketFactory.getDefault());
}
return new OkHttpClient.Builder()
.connectionSpecs(createConnectionSpecs(ConnectionSpec.RESTRICTED_TLS, false))
.socketFactory(sDelegatingSocketFactory);
}
@SuppressLint("BadHostnameVerifier")
static OkHttpClient.Builder getUnsafeClientBuilder() {
OkHttpClient.Builder builder = getSafeClientBuilder();
try {
if (sSSLSocketFactory == null) {
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new X509TrustManager[]{TRUST_ALL_CERTS}, null);
sSSLSocketFactory = sslContext.getSocketFactory();
}
builder.connectionSpecs(createConnectionSpecs(ConnectionSpec.MODERN_TLS, true));
builder.sslSocketFactory(sSSLSocketFactory, TRUST_ALL_CERTS);
builder.hostnameVerifier((hostname, session) -> hostname != null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
// Ignore
}
return builder;
}
private static List<ConnectionSpec> createConnectionSpecs(ConnectionSpec tlsSpec,
boolean forceAllCipherSuites) {
ConnectionSpec.Builder spec = new ConnectionSpec.Builder(tlsSpec);
if (Build.VERSION.RELEASE.equals("7.0") || forceAllCipherSuites) {
// There is a bug in Android 7.0 (https://issuetracker.google.com/issues/37122132)
// that only supports the prime256v1 elliptic curve. So in just release the
// cipher requirements if we are in that case.
spec.allEnabledCipherSuites();
}
return Collections.singletonList(spec.build());
}
}
| Allow cleartext connection specs for http connections
Signed-off-by: Jorge Ruesga <[email protected]>
| gerrit/src/main/java/com/ruesga/rview/gerrit/OkHttpHelper.java | Allow cleartext connection specs for http connections |
|
Java | apache-2.0 | 0419d37341cde77cb3453fbd889d6c31f941f7e5 | 0 | apache/kandula | /*
* Copyright 2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.kandula.participant.standalone;
import java.rmi.RemoteException;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.kandula.KandulaException;
import org.apache.kandula.coordinator.context.ActivityContext;
import org.apache.kandula.coordinator.context.ContextFactory;
import org.apache.kandula.coordinator.context.at.ATActivityContext;
import org.apache.kandula.storage.StorageFactory;
import org.apache.kandula.storage.Store;
import org.apache.kandula.utility.EndpointReferenceFactory;
import org.apache.kandula.wscoor.ActivationCoordinatorPortTypeRawXMLStub;
import org.apache.kandula.wscoor.RegistrationCoordinatorPortTypeRawXMLStub;
/**
* @author Dasarath Weeratunge
* @author <a href="mailto:[email protected]"> Thilina Gunarathne </a>
*/
public class TransactionManager {
private ThreadLocal threadInfo;
//till we get reply to reference properties correctly in Axis 2 Addressing
public static String tempID;
public TransactionManager(String coordinationType,
EndpointReference coordEPR) throws KandulaException {
threadInfo = new ThreadLocal();
ActivityContext context = ContextFactory.getInstance().createActivity(
coordinationType, coordEPR);
if (threadInfo.get() != null)
throw new IllegalStateException();
threadInfo.set(context.getProperty(ATActivityContext.REQUESTER_ID));
//TODO remove this when we get replyTo reference properties correctly
tempID = (String) context.getProperty(ATActivityContext.REQUESTER_ID);
Store store = StorageFactory.getInstance().getStore();
store.putContext(context.getProperty(ATActivityContext.REQUESTER_ID),
context);
}
/**
* @throws Exception
*/
public void begin() throws Exception {
ActivityContext context = getTransaction();
String id = (String) context
.getProperty(ATActivityContext.REQUESTER_ID);
threadInfo.set(id);
ActivationCoordinatorPortTypeRawXMLStub activationCoordinator = new ActivationCoordinatorPortTypeRawXMLStub(
".", (EndpointReference) context
.getProperty(ATActivityContext.ACTIVATION_EPR));
activationCoordinator.createCoordinationContextOperation(
org.apache.kandula.Constants.WS_AT, id);
while (context.getCoordinationContext() == null) {
//allow other threads to execute
Thread.sleep(10);
}
RegistrationCoordinatorPortTypeRawXMLStub registrationCoordinator = new RegistrationCoordinatorPortTypeRawXMLStub(
".", context.getCoordinationContext().getRegistrationService());
EndpointReference registrationRequeterPortEPR = EndpointReferenceFactory
.getInstance().getCompletionParticipantEndpoint(id);
registrationCoordinator.RegisterOperation(
org.apache.kandula.Constants.WS_AT_COMPLETION,
registrationRequeterPortEPR, id);
while (true) {
Thread.sleep(10);
}
}
public void commit() throws RemoteException {
// Transaction tx= getTransaction();
// if (tx == null)
// throw new IllegalStateException();
// forget();
// tx.commit();
}
public void rollback() throws RemoteException {
// Transaction tx= getTransaction();
// if (tx == null)
// throw new IllegalStateException();
// forget();
// tx.rollback();
}
// public Transaction suspend() {
// Transaction tx= getTransaction();
// forget();
// return tx;
// }
//
// public void resume(Transaction tx) {
// if (threadInfo.get() != null)
// throw new IllegalStateException();
// else
// threadInfo.set(tx);
// }
//
// public void forget() {
// threadInfo.set(null);
// }
public ActivityContext getTransaction() throws KandulaException {
Object key = threadInfo.get();
ActivityContext context = StorageFactory.getInstance().getStore()
.getContext(key);
if (context == null) {
throw new KandulaException("IllegalState");
}
return context;
}
} | src/org/apache/kandula/participant/standalone/TransactionManager.java | /*
* Copyright 2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.kandula.participant.standalone;
import java.rmi.RemoteException;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.kandula.KandulaException;
import org.apache.kandula.coordinator.context.ActivityContext;
import org.apache.kandula.coordinator.context.ContextFactory;
import org.apache.kandula.coordinator.context.at.ATActivityContext;
import org.apache.kandula.storage.StorageFactory;
import org.apache.kandula.storage.Store;
import org.apache.kandula.wscoor.ActivationCoordinatorPortTypeRawXMLStub;
/**
* @author Dasarath Weeratunge
* @author <a href="mailto:[email protected]"> Thilina Gunarathne </a>
*/
public class TransactionManager {
ThreadLocal threadInfo;
//till we get reply to reference properties correctly in Axis 2 Addressing
public static String tempID;
public TransactionManager(String coordinationType,
EndpointReference coordEPR) throws KandulaException {
threadInfo = new ThreadLocal();
ActivityContext context = ContextFactory.getInstance().createActivity(
coordinationType, coordEPR);
if (threadInfo.get() != null)
throw new IllegalStateException();
threadInfo.set(context.getProperty(ATActivityContext.REQUESTER_ID));
//TODO remove this when we get replyTo reference properties correctly
tempID = (String)context.getProperty(ATActivityContext.REQUESTER_ID);
Store store = StorageFactory.getInstance().getStore();
store.putContext(context.getProperty(ATActivityContext.REQUESTER_ID),
context);
}
/**
* @throws Exception
*/
public void begin() throws Exception {
ActivityContext context = getTransaction();
String id = (String) context
.getProperty(ATActivityContext.REQUESTER_ID);
threadInfo.set(id);
ActivationCoordinatorPortTypeRawXMLStub activationCoordinator = new ActivationCoordinatorPortTypeRawXMLStub(
".", (EndpointReference) context
.getProperty(ATActivityContext.ACTIVATION_EPR));
activationCoordinator.createCoordinationContextOperation(
org.apache.kandula.Constants.WS_AT, id);
while (context.getCoordinationContext()==null)
{
//allow other threads to execute
Thread.sleep(10);
}
}
public void commit() throws RemoteException {
// Transaction tx= getTransaction();
// if (tx == null)
// throw new IllegalStateException();
// forget();
// tx.commit();
}
public void rollback() throws RemoteException {
// Transaction tx= getTransaction();
// if (tx == null)
// throw new IllegalStateException();
// forget();
// tx.rollback();
}
// public Transaction suspend() {
// Transaction tx= getTransaction();
// forget();
// return tx;
// }
//
// public void resume(Transaction tx) {
// if (threadInfo.get() != null)
// throw new IllegalStateException();
// else
// threadInfo.set(tx);
// }
//
// public void forget() {
// threadInfo.set(null);
// }
public ActivityContext getTransaction() throws KandulaException{
Object key = threadInfo.get();
ActivityContext context = StorageFactory.getInstance().getStore()
.getContext(key);
if (context == null) {
throw new KandulaException("IllegalState");
}
return context;
}
} | Adding new registration endpoint support
git-svn-id: 826ea26f63ac7a79fb570b066df16dcd4a7695b7@280133 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/kandula/participant/standalone/TransactionManager.java | Adding new registration endpoint support |
|
Java | apache-2.0 | 486b290863a66641b0ec30dbf2d9e349733cae44 | 0 | amyvmiwei/hbase,toshimasa-nasu/hbase,gustavoanatoly/hbase,mahak/hbase,andrewmains12/hbase,SeekerResource/hbase,juwi/hbase,Guavus/hbase,toshimasa-nasu/hbase,JingchengDu/hbase,mapr/hbase,joshelser/hbase,francisliu/hbase,Eshcar/hbase,drewpope/hbase,vincentpoon/hbase,narendragoyal/hbase,ChinmaySKulkarni/hbase,lshmouse/hbase,toshimasa-nasu/hbase,mapr/hbase,lshmouse/hbase,Apache9/hbase,Eshcar/hbase,juwi/hbase,andrewmains12/hbase,narendragoyal/hbase,apurtell/hbase,HubSpot/hbase,StackVista/hbase,juwi/hbase,drewpope/hbase,intel-hadoop/hbase-rhino,JingchengDu/hbase,francisliu/hbase,JingchengDu/hbase,Eshcar/hbase,SeekerResource/hbase,ChinmaySKulkarni/hbase,ibmsoe/hbase,vincentpoon/hbase,justintung/hbase,Apache9/hbase,apurtell/hbase,narendragoyal/hbase,Apache9/hbase,justintung/hbase,intel-hadoop/hbase-rhino,mahak/hbase,Eshcar/hbase,HubSpot/hbase,ChinmaySKulkarni/hbase,ibmsoe/hbase,Eshcar/hbase,Eshcar/hbase,francisliu/hbase,narendragoyal/hbase,apurtell/hbase,amyvmiwei/hbase,andrewmains12/hbase,bijugs/hbase,StackVista/hbase,justintung/hbase,mahak/hbase,toshimasa-nasu/hbase,Guavus/hbase,Guavus/hbase,drewpope/hbase,ndimiduk/hbase,Apache9/hbase,justintung/hbase,andrewmains12/hbase,justintung/hbase,ndimiduk/hbase,narendragoyal/hbase,lshmouse/hbase,intel-hadoop/hbase-rhino,amyvmiwei/hbase,mahak/hbase,apurtell/hbase,gustavoanatoly/hbase,vincentpoon/hbase,ibmsoe/hbase,ultratendency/hbase,drewpope/hbase,amyvmiwei/hbase,amyvmiwei/hbase,ndimiduk/hbase,SeekerResource/hbase,mapr/hbase,ndimiduk/hbase,andrewmains12/hbase,bijugs/hbase,narendragoyal/hbase,narendragoyal/hbase,ultratendency/hbase,SeekerResource/hbase,lshmouse/hbase,intel-hadoop/hbase-rhino,mahak/hbase,JingchengDu/hbase,narendragoyal/hbase,ChinmaySKulkarni/hbase,joshelser/hbase,ibmsoe/hbase,SeekerResource/hbase,ibmsoe/hbase,amyvmiwei/hbase,HubSpot/hbase,bijugs/hbase,justintung/hbase,joshelser/hbase,vincentpoon/hbase,francisliu/hbase,juwi/hbase,intel-hadoop/hbase-rhino,francisliu/hbase,HubSpot/hbase,StackVista/hbase,StackVista/hbase,ndimiduk/hbase,Eshcar/hbase,JingchengDu/hbase,SeekerResource/hbase,HubSpot/hbase,joshelser/hbase,lshmouse/hbase,StackVista/hbase,bijugs/hbase,ultratendency/hbase,JingchengDu/hbase,lshmouse/hbase,mahak/hbase,andrewmains12/hbase,intel-hadoop/hbase-rhino,juwi/hbase,joshelser/hbase,bijugs/hbase,Guavus/hbase,mapr/hbase,ChinmaySKulkarni/hbase,StackVista/hbase,ndimiduk/hbase,juwi/hbase,HubSpot/hbase,vincentpoon/hbase,ndimiduk/hbase,apurtell/hbase,apurtell/hbase,ibmsoe/hbase,gustavoanatoly/hbase,justintung/hbase,francisliu/hbase,drewpope/hbase,drewpope/hbase,JingchengDu/hbase,toshimasa-nasu/hbase,gustavoanatoly/hbase,JingchengDu/hbase,intel-hadoop/hbase-rhino,amyvmiwei/hbase,Apache9/hbase,StackVista/hbase,Eshcar/hbase,ultratendency/hbase,francisliu/hbase,JingchengDu/hbase,justintung/hbase,Eshcar/hbase,amyvmiwei/hbase,ultratendency/hbase,francisliu/hbase,gustavoanatoly/hbase,vincentpoon/hbase,amyvmiwei/hbase,drewpope/hbase,intel-hadoop/hbase-rhino,ChinmaySKulkarni/hbase,mahak/hbase,StackVista/hbase,mahak/hbase,amyvmiwei/hbase,ibmsoe/hbase,Guavus/hbase,apurtell/hbase,mapr/hbase,Apache9/hbase,Apache9/hbase,apurtell/hbase,Guavus/hbase,SeekerResource/hbase,francisliu/hbase,ultratendency/hbase,mapr/hbase,ibmsoe/hbase,vincentpoon/hbase,justintung/hbase,mahak/hbase,Guavus/hbase,ChinmaySKulkarni/hbase,lshmouse/hbase,HubSpot/hbase,SeekerResource/hbase,andrewmains12/hbase,intel-hadoop/hbase-rhino,lshmouse/hbase,ultratendency/hbase,apurtell/hbase,ultratendency/hbase,bijugs/hbase,justintung/hbase,gustavoanatoly/hbase,joshelser/hbase,drewpope/hbase,toshimasa-nasu/hbase,joshelser/hbase,JingchengDu/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,StackVista/hbase,ultratendency/hbase,juwi/hbase,drewpope/hbase,ndimiduk/hbase,andrewmains12/hbase,vincentpoon/hbase,ibmsoe/hbase,StackVista/hbase,bijugs/hbase,francisliu/hbase,juwi/hbase,Apache9/hbase,andrewmains12/hbase,apurtell/hbase,HubSpot/hbase,vincentpoon/hbase,HubSpot/hbase,lshmouse/hbase,Guavus/hbase,mapr/hbase,bijugs/hbase,SeekerResource/hbase,Guavus/hbase,joshelser/hbase,ultratendency/hbase,gustavoanatoly/hbase,intel-hadoop/hbase-rhino,gustavoanatoly/hbase,Guavus/hbase,toshimasa-nasu/hbase,bijugs/hbase,lshmouse/hbase,SeekerResource/hbase,Apache9/hbase,ndimiduk/hbase,narendragoyal/hbase,HubSpot/hbase,ndimiduk/hbase,mapr/hbase,gustavoanatoly/hbase,mapr/hbase,joshelser/hbase,gustavoanatoly/hbase,Eshcar/hbase,ibmsoe/hbase,andrewmains12/hbase,ChinmaySKulkarni/hbase,vincentpoon/hbase,mahak/hbase,joshelser/hbase,toshimasa-nasu/hbase,toshimasa-nasu/hbase,narendragoyal/hbase,juwi/hbase,Apache9/hbase,bijugs/hbase | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.client;
import com.google.protobuf.ByteString;
import com.google.protobuf.ServiceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Abortable;
import org.apache.hadoop.hbase.ClusterStatus;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
import org.apache.hadoop.hbase.catalog.MetaReader;
import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitor;
import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitorBase;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.exceptions.FailedLogCloseException;
import org.apache.hadoop.hbase.exceptions.HBaseSnapshotException;
import org.apache.hadoop.hbase.exceptions.MasterNotRunningException;
import org.apache.hadoop.hbase.exceptions.NotServingRegionException;
import org.apache.hadoop.hbase.exceptions.RegionException;
import org.apache.hadoop.hbase.exceptions.RestoreSnapshotException;
import org.apache.hadoop.hbase.exceptions.SnapshotCreationException;
import org.apache.hadoop.hbase.exceptions.TableExistsException;
import org.apache.hadoop.hbase.exceptions.TableNotEnabledException;
import org.apache.hadoop.hbase.exceptions.TableNotFoundException;
import org.apache.hadoop.hbase.exceptions.UnknownRegionException;
import org.apache.hadoop.hbase.exceptions.UnknownSnapshotException;
import org.apache.hadoop.hbase.exceptions.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
import org.apache.hadoop.hbase.ipc.MasterCoprocessorRpcChannel;
import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.protobuf.RequestConverter;
import org.apache.hadoop.hbase.protobuf.ResponseConverter;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionResponse;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CompactRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.FlushRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse.CompactionState;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterResponse;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.StopServerRequest;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.TableSchema;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.AddColumnRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.AssignRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.CreateTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.DeleteColumnRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.DeleteSnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.DeleteTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.DisableTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.EnableTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.IsRestoreSnapshotDoneRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.IsRestoreSnapshotDoneResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.IsSnapshotDoneRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.IsSnapshotDoneResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.ListSnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.ModifyColumnRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.ModifyTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.MoveRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.RestoreSnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.RestoreSnapshotResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.SetBalancerRunningRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.ShutdownRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.StopMasterRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.TakeSnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.TakeSnapshotResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.UnassignRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetClusterStatusRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetSchemaAlterStatusRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetSchemaAlterStatusResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsResponse;
import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
import org.apache.hadoop.hbase.util.Addressing;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.util.StringUtils;
import org.apache.zookeeper.KeeperException;
import java.io.Closeable;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
/**
* Provides an interface to manage HBase database table metadata + general
* administrative functions. Use HBaseAdmin to create, drop, list, enable and
* disable tables. Use it also to add and drop table column families.
*
* <p>See {@link HTable} to add, update, and delete data from an individual table.
* <p>Currently HBaseAdmin instances are not expected to be long-lived. For
* example, an HBaseAdmin instance will not ride over a Master restart.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class HBaseAdmin implements Abortable, Closeable {
private static final Log LOG = LogFactory.getLog(HBaseAdmin.class);
// We use the implementation class rather then the interface because we
// need the package protected functions to get the connection to master
private HConnection connection;
private volatile Configuration conf;
private final long pause;
private final int numRetries;
// Some operations can take a long time such as disable of big table.
// numRetries is for 'normal' stuff... Multiply by this factor when
// want to wait a long time.
private final int retryLongerMultiplier;
private boolean aborted;
/**
* Constructor.
* See {@link #HBaseAdmin(HConnection connection)}
*
* @param c Configuration object. Copied internally.
*/
public HBaseAdmin(Configuration c)
throws MasterNotRunningException, ZooKeeperConnectionException {
// Will not leak connections, as the new implementation of the constructor
// does not throw exceptions anymore.
this(HConnectionManager.getConnection(new Configuration(c)));
}
/**
* Constructor for externally managed HConnections.
* The connection to master will be created when required by admin functions.
*
* @param connection The HConnection instance to use
* @throws MasterNotRunningException, ZooKeeperConnectionException are not
* thrown anymore but kept into the interface for backward api compatibility
*/
public HBaseAdmin(HConnection connection)
throws MasterNotRunningException, ZooKeeperConnectionException {
this.conf = connection.getConfiguration();
this.connection = connection;
this.pause = this.conf.getLong("hbase.client.pause", 1000);
this.numRetries = this.conf.getInt("hbase.client.retries.number", 10);
this.retryLongerMultiplier = this.conf.getInt(
"hbase.client.retries.longer.multiplier", 10);
}
/**
* @return A new CatalogTracker instance; call {@link #cleanupCatalogTracker(CatalogTracker)}
* to cleanup the returned catalog tracker.
* @throws org.apache.hadoop.hbase.exceptions.ZooKeeperConnectionException
* @throws IOException
* @see #cleanupCatalogTracker(CatalogTracker)
*/
private synchronized CatalogTracker getCatalogTracker()
throws ZooKeeperConnectionException, IOException {
CatalogTracker ct = null;
try {
ct = new CatalogTracker(this.conf);
ct.start();
} catch (InterruptedException e) {
// Let it out as an IOE for now until we redo all so tolerate IEs
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e);
}
return ct;
}
private void cleanupCatalogTracker(final CatalogTracker ct) {
ct.stop();
}
@Override
public void abort(String why, Throwable e) {
// Currently does nothing but throw the passed message and exception
this.aborted = true;
throw new RuntimeException(why, e);
}
@Override
public boolean isAborted(){
return this.aborted;
}
/** @return HConnection used by this object. */
public HConnection getConnection() {
return connection;
}
/** @return - true if the master server is running. Throws an exception
* otherwise.
* @throws ZooKeeperConnectionException
* @throws MasterNotRunningException
*/
public boolean isMasterRunning()
throws MasterNotRunningException, ZooKeeperConnectionException {
return connection.isMasterRunning();
}
/**
* @param tableName Table to check.
* @return True if table exists already.
* @throws IOException
*/
public boolean tableExists(final String tableName)
throws IOException {
boolean b = false;
CatalogTracker ct = getCatalogTracker();
try {
b = MetaReader.tableExists(ct, tableName);
} finally {
cleanupCatalogTracker(ct);
}
return b;
}
/**
* @param tableName Table to check.
* @return True if table exists already.
* @throws IOException
*/
public boolean tableExists(final byte [] tableName)
throws IOException {
return tableExists(Bytes.toString(tableName));
}
/**
* List all the userspace tables. In other words, scan the META table.
*
* If we wanted this to be really fast, we could implement a special
* catalog table that just contains table names and their descriptors.
* Right now, it only exists as part of the META table's region info.
*
* @return - returns an array of HTableDescriptors
* @throws IOException if a remote or network exception occurs
*/
public HTableDescriptor[] listTables() throws IOException {
return this.connection.listTables();
}
/**
* List all the userspace tables matching the given pattern.
*
* @param pattern The compiled regular expression to match against
* @return - returns an array of HTableDescriptors
* @throws IOException if a remote or network exception occurs
* @see #listTables()
*/
public HTableDescriptor[] listTables(Pattern pattern) throws IOException {
List<HTableDescriptor> matched = new LinkedList<HTableDescriptor>();
HTableDescriptor[] tables = listTables();
for (HTableDescriptor table : tables) {
if (pattern.matcher(table.getNameAsString()).matches()) {
matched.add(table);
}
}
return matched.toArray(new HTableDescriptor[matched.size()]);
}
/**
* List all the userspace tables matching the given regular expression.
*
* @param regex The regular expression to match against
* @return - returns an array of HTableDescriptors
* @throws IOException if a remote or network exception occurs
* @see #listTables(java.util.regex.Pattern)
*/
public HTableDescriptor[] listTables(String regex) throws IOException {
return listTables(Pattern.compile(regex));
}
/**
* Method for getting the tableDescriptor
* @param tableName as a byte []
* @return the tableDescriptor
* @throws TableNotFoundException
* @throws IOException if a remote or network exception occurs
*/
public HTableDescriptor getTableDescriptor(final byte [] tableName)
throws TableNotFoundException, IOException {
return this.connection.getHTableDescriptor(tableName);
}
private long getPauseTime(int tries) {
int triesCount = tries;
if (triesCount >= HConstants.RETRY_BACKOFF.length) {
triesCount = HConstants.RETRY_BACKOFF.length - 1;
}
return this.pause * HConstants.RETRY_BACKOFF[triesCount];
}
/**
* Creates a new table.
* Synchronous operation.
*
* @param desc table descriptor for table
*
* @throws IllegalArgumentException if the table name is reserved
* @throws MasterNotRunningException if master is not running
* @throws TableExistsException if table already exists (If concurrent
* threads, the table may have been created between test-for-existence
* and attempt-at-creation).
* @throws IOException if a remote or network exception occurs
*/
public void createTable(HTableDescriptor desc)
throws IOException {
createTable(desc, null);
}
/**
* Creates a new table with the specified number of regions. The start key
* specified will become the end key of the first region of the table, and
* the end key specified will become the start key of the last region of the
* table (the first region has a null start key and the last region has a
* null end key).
*
* BigInteger math will be used to divide the key range specified into
* enough segments to make the required number of total regions.
*
* Synchronous operation.
*
* @param desc table descriptor for table
* @param startKey beginning of key range
* @param endKey end of key range
* @param numRegions the total number of regions to create
*
* @throws IllegalArgumentException if the table name is reserved
* @throws MasterNotRunningException if master is not running
* @throws org.apache.hadoop.hbase.exceptions.TableExistsException if table already exists (If concurrent
* threads, the table may have been created between test-for-existence
* and attempt-at-creation).
* @throws IOException
*/
public void createTable(HTableDescriptor desc, byte [] startKey,
byte [] endKey, int numRegions)
throws IOException {
HTableDescriptor.isLegalTableName(desc.getName());
if(numRegions < 3) {
throw new IllegalArgumentException("Must create at least three regions");
} else if(Bytes.compareTo(startKey, endKey) >= 0) {
throw new IllegalArgumentException("Start key must be smaller than end key");
}
byte [][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3);
if(splitKeys == null || splitKeys.length != numRegions - 1) {
throw new IllegalArgumentException("Unable to split key range into enough regions");
}
createTable(desc, splitKeys);
}
/**
* Creates a new table with an initial set of empty regions defined by the
* specified split keys. The total number of regions created will be the
* number of split keys plus one. Synchronous operation.
* Note : Avoid passing empty split key.
*
* @param desc table descriptor for table
* @param splitKeys array of split keys for the initial regions of the table
*
* @throws IllegalArgumentException if the table name is reserved, if the split keys
* are repeated and if the split key has empty byte array.
* @throws MasterNotRunningException if master is not running
* @throws org.apache.hadoop.hbase.exceptions.TableExistsException if table already exists (If concurrent
* threads, the table may have been created between test-for-existence
* and attempt-at-creation).
* @throws IOException
*/
public void createTable(final HTableDescriptor desc, byte [][] splitKeys)
throws IOException {
HTableDescriptor.isLegalTableName(desc.getName());
try {
createTableAsync(desc, splitKeys);
} catch (SocketTimeoutException ste) {
LOG.warn("Creating " + desc.getNameAsString() + " took too long", ste);
}
int numRegs = splitKeys == null ? 1 : splitKeys.length + 1;
int prevRegCount = 0;
boolean doneWithMetaScan = false;
for (int tries = 0; tries < this.numRetries * this.retryLongerMultiplier;
++tries) {
if (!doneWithMetaScan) {
// Wait for new table to come on-line
final AtomicInteger actualRegCount = new AtomicInteger(0);
MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
@Override
public boolean processRow(Result rowResult) throws IOException {
HRegionInfo info = HRegionInfo.getHRegionInfo(rowResult);
if (info == null) {
LOG.warn("No serialized HRegionInfo in " + rowResult);
return true;
}
if (!(Bytes.equals(info.getTableName(), desc.getName()))) {
return false;
}
ServerName serverName = HRegionInfo.getServerName(rowResult);
// Make sure that regions are assigned to server
if (!(info.isOffline() || info.isSplit()) && serverName != null
&& serverName.getHostAndPort() != null) {
actualRegCount.incrementAndGet();
}
return true;
}
};
MetaScanner.metaScan(conf, visitor, desc.getName());
if (actualRegCount.get() != numRegs) {
if (tries == this.numRetries * this.retryLongerMultiplier - 1) {
throw new RegionOfflineException("Only " + actualRegCount.get() +
" of " + numRegs + " regions are online; retries exhausted.");
}
try { // Sleep
Thread.sleep(getPauseTime(tries));
} catch (InterruptedException e) {
throw new InterruptedIOException("Interrupted when opening" +
" regions; " + actualRegCount.get() + " of " + numRegs +
" regions processed so far");
}
if (actualRegCount.get() > prevRegCount) { // Making progress
prevRegCount = actualRegCount.get();
tries = -1;
}
} else {
doneWithMetaScan = true;
tries = -1;
}
} else if (isTableEnabled(desc.getName())) {
return;
} else {
try { // Sleep
Thread.sleep(getPauseTime(tries));
} catch (InterruptedException e) {
throw new InterruptedIOException("Interrupted when waiting" +
" for table to be enabled; meta scan was done");
}
}
}
throw new TableNotEnabledException(
"Retries exhausted while still waiting for table: "
+ desc.getNameAsString() + " to be enabled");
}
/**
* Creates a new table but does not block and wait for it to come online.
* Asynchronous operation. To check if the table exists, use
* {@link #isTableAvailable} -- it is not safe to create an HTable
* instance to this table before it is available.
* Note : Avoid passing empty split key.
* @param desc table descriptor for table
*
* @throws IllegalArgumentException Bad table name, if the split keys
* are repeated and if the split key has empty byte array.
* @throws MasterNotRunningException if master is not running
* @throws org.apache.hadoop.hbase.exceptions.TableExistsException if table already exists (If concurrent
* threads, the table may have been created between test-for-existence
* and attempt-at-creation).
* @throws IOException
*/
public void createTableAsync(
final HTableDescriptor desc, final byte [][] splitKeys)
throws IOException {
HTableDescriptor.isLegalTableName(desc.getName());
if(splitKeys != null && splitKeys.length > 0) {
Arrays.sort(splitKeys, Bytes.BYTES_COMPARATOR);
// Verify there are no duplicate split keys
byte [] lastKey = null;
for(byte [] splitKey : splitKeys) {
if (Bytes.compareTo(splitKey, HConstants.EMPTY_BYTE_ARRAY) == 0) {
throw new IllegalArgumentException(
"Empty split key must not be passed in the split keys.");
}
if(lastKey != null && Bytes.equals(splitKey, lastKey)) {
throw new IllegalArgumentException("All split keys must be unique, " +
"found duplicate: " + Bytes.toStringBinary(splitKey) +
", " + Bytes.toStringBinary(lastKey));
}
lastKey = splitKey;
}
}
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
CreateTableRequest request = RequestConverter.buildCreateTableRequest(desc, splitKeys);
masterAdmin.createTable(null, request);
return null;
}
});
}
/**
* Deletes a table.
* Synchronous operation.
*
* @param tableName name of table to delete
* @throws IOException if a remote or network exception occurs
*/
public void deleteTable(final String tableName) throws IOException {
deleteTable(Bytes.toBytes(tableName));
}
/**
* Deletes a table.
* Synchronous operation.
*
* @param tableName name of table to delete
* @throws IOException if a remote or network exception occurs
*/
public void deleteTable(final byte [] tableName) throws IOException {
HTableDescriptor.isLegalTableName(tableName);
HRegionLocation firstMetaServer = getFirstMetaServerForTable(tableName);
boolean tableExists = true;
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
DeleteTableRequest req = RequestConverter.buildDeleteTableRequest(tableName);
masterAdmin.deleteTable(null,req);
return null;
}
});
// Wait until all regions deleted
ClientProtocol server =
connection.getClient(firstMetaServer.getServerName());
for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
try {
Scan scan = MetaReader.getScanForTableName(tableName);
scan.addColumn(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER);
ScanRequest request = RequestConverter.buildScanRequest(
firstMetaServer.getRegionInfo().getRegionName(), scan, 1, true);
Result[] values = null;
// Get a batch at a time.
try {
ScanResponse response = server.scan(null, request);
values = ResponseConverter.getResults(response);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
// let us wait until .META. table is updated and
// HMaster removes the table from its HTableDescriptors
if (values == null || values.length == 0) {
tableExists = false;
GetTableDescriptorsResponse htds;
MasterMonitorKeepAliveConnection master = connection.getKeepAliveMasterMonitor();
try {
GetTableDescriptorsRequest req =
RequestConverter.buildGetTableDescriptorsRequest(null);
htds = master.getTableDescriptors(null, req);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
} finally {
master.close();
}
for (TableSchema ts : htds.getTableSchemaList()) {
if (Bytes.equals(tableName, ts.getName().toByteArray())) {
tableExists = true;
break;
}
}
if (!tableExists) {
break;
}
}
} catch (IOException ex) {
if(tries == numRetries - 1) { // no more tries left
if (ex instanceof RemoteException) {
throw ((RemoteException) ex).unwrapRemoteException();
}else {
throw ex;
}
}
}
try {
Thread.sleep(getPauseTime(tries));
} catch (InterruptedException e) {
// continue
}
}
if (tableExists) {
throw new IOException("Retries exhausted, it took too long to wait"+
" for the table " + Bytes.toString(tableName) + " to be deleted.");
}
// Delete cached information to prevent clients from using old locations
this.connection.clearRegionCache(tableName);
LOG.info("Deleted " + Bytes.toString(tableName));
}
/**
* Deletes tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.lang.String)} and
* {@link #deleteTable(byte[])}
*
* @param regex The regular expression to match table names against
* @return Table descriptors for tables that couldn't be deleted
* @throws IOException
* @see #deleteTables(java.util.regex.Pattern)
* @see #deleteTable(java.lang.String)
*/
public HTableDescriptor[] deleteTables(String regex) throws IOException {
return deleteTables(Pattern.compile(regex));
}
/**
* Delete tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and
* {@link #deleteTable(byte[])}
*
* @param pattern The pattern to match table names against
* @return Table descriptors for tables that couldn't be deleted
* @throws IOException
*/
public HTableDescriptor[] deleteTables(Pattern pattern) throws IOException {
List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
for (HTableDescriptor table : listTables(pattern)) {
try {
deleteTable(table.getName());
} catch (IOException ex) {
LOG.info("Failed to delete table " + table.getNameAsString(), ex);
failed.add(table);
}
}
return failed.toArray(new HTableDescriptor[failed.size()]);
}
public void enableTable(final String tableName)
throws IOException {
enableTable(Bytes.toBytes(tableName));
}
/**
* Enable a table. May timeout. Use {@link #enableTableAsync(byte[])}
* and {@link #isTableEnabled(byte[])} instead.
* The table has to be in disabled state for it to be enabled.
* @param tableName name of the table
* @throws IOException if a remote or network exception occurs
* There could be couple types of IOException
* TableNotFoundException means the table doesn't exist.
* TableNotDisabledException means the table isn't in disabled state.
* @see #isTableEnabled(byte[])
* @see #disableTable(byte[])
* @see #enableTableAsync(byte[])
*/
public void enableTable(final byte [] tableName)
throws IOException {
enableTableAsync(tableName);
// Wait until all regions are enabled
waitUntilTableIsEnabled(tableName);
LOG.info("Enabled table " + Bytes.toString(tableName));
}
/**
* Wait for the table to be enabled and available
* If enabling the table exceeds the retry period, an exception is thrown.
* @param tableName name of the table
* @throws IOException if a remote or network exception occurs or
* table is not enabled after the retries period.
*/
private void waitUntilTableIsEnabled(final byte[] tableName) throws IOException {
boolean enabled = false;
long start = EnvironmentEdgeManager.currentTimeMillis();
for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
enabled = isTableEnabled(tableName) && isTableAvailable(tableName);
if (enabled) {
break;
}
long sleep = getPauseTime(tries);
if (LOG.isDebugEnabled()) {
LOG.debug("Sleeping= " + sleep + "ms, waiting for all regions to be " +
"enabled in " + Bytes.toString(tableName));
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// Do this conversion rather than let it out because do not want to
// change the method signature.
throw new IOException("Interrupted", e);
}
}
if (!enabled) {
long msec = EnvironmentEdgeManager.currentTimeMillis() - start;
throw new IOException("Table '" + Bytes.toString(tableName) +
"' not yet enabled, after " + msec + "ms.");
}
}
public void enableTableAsync(final String tableName)
throws IOException {
enableTableAsync(Bytes.toBytes(tableName));
}
/**
* Brings a table on-line (enables it). Method returns immediately though
* enable of table may take some time to complete, especially if the table
* is large (All regions are opened as part of enabling process). Check
* {@link #isTableEnabled(byte[])} to learn when table is fully online. If
* table is taking too long to online, check server logs.
* @param tableName
* @throws IOException
* @since 0.90.0
*/
public void enableTableAsync(final byte [] tableName)
throws IOException {
HTableDescriptor.isLegalTableName(tableName);
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
LOG.info("Started enable of " + Bytes.toString(tableName));
EnableTableRequest req = RequestConverter.buildEnableTableRequest(tableName);
masterAdmin.enableTable(null,req);
return null;
}
});
}
/**
* Enable tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.lang.String)} and
* {@link #enableTable(byte[])}
*
* @param regex The regular expression to match table names against
* @throws IOException
* @see #enableTables(java.util.regex.Pattern)
* @see #enableTable(java.lang.String)
*/
public HTableDescriptor[] enableTables(String regex) throws IOException {
return enableTables(Pattern.compile(regex));
}
/**
* Enable tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and
* {@link #enableTable(byte[])}
*
* @param pattern The pattern to match table names against
* @throws IOException
*/
public HTableDescriptor[] enableTables(Pattern pattern) throws IOException {
List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
for (HTableDescriptor table : listTables(pattern)) {
if (isTableDisabled(table.getName())) {
try {
enableTable(table.getName());
} catch (IOException ex) {
LOG.info("Failed to enable table " + table.getNameAsString(), ex);
failed.add(table);
}
}
}
return failed.toArray(new HTableDescriptor[failed.size()]);
}
public void disableTableAsync(final String tableName) throws IOException {
disableTableAsync(Bytes.toBytes(tableName));
}
/**
* Starts the disable of a table. If it is being served, the master
* will tell the servers to stop serving it. This method returns immediately.
* The disable of a table can take some time if the table is large (all
* regions are closed as part of table disable operation).
* Call {@link #isTableDisabled(byte[])} to check for when disable completes.
* If table is taking too long to online, check server logs.
* @param tableName name of table
* @throws IOException if a remote or network exception occurs
* @see #isTableDisabled(byte[])
* @see #isTableEnabled(byte[])
* @since 0.90.0
*/
public void disableTableAsync(final byte [] tableName) throws IOException {
HTableDescriptor.isLegalTableName(tableName);
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
LOG.info("Started disable of " + Bytes.toString(tableName));
DisableTableRequest req = RequestConverter.buildDisableTableRequest(tableName);
masterAdmin.disableTable(null,req);
return null;
}
});
}
public void disableTable(final String tableName)
throws IOException {
disableTable(Bytes.toBytes(tableName));
}
/**
* Disable table and wait on completion. May timeout eventually. Use
* {@link #disableTableAsync(byte[])} and {@link #isTableDisabled(String)}
* instead.
* The table has to be in enabled state for it to be disabled.
* @param tableName
* @throws IOException
* There could be couple types of IOException
* TableNotFoundException means the table doesn't exist.
* TableNotEnabledException means the table isn't in enabled state.
*/
public void disableTable(final byte [] tableName)
throws IOException {
disableTableAsync(tableName);
// Wait until table is disabled
boolean disabled = false;
for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
disabled = isTableDisabled(tableName);
if (disabled) {
break;
}
long sleep = getPauseTime(tries);
if (LOG.isDebugEnabled()) {
LOG.debug("Sleeping= " + sleep + "ms, waiting for all regions to be " +
"disabled in " + Bytes.toString(tableName));
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
// Do this conversion rather than let it out because do not want to
// change the method signature.
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e);
}
}
if (!disabled) {
throw new RegionException("Retries exhausted, it took too long to wait"+
" for the table " + Bytes.toString(tableName) + " to be disabled.");
}
LOG.info("Disabled " + Bytes.toString(tableName));
}
/**
* Disable tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.lang.String)} and
* {@link #disableTable(byte[])}
*
* @param regex The regular expression to match table names against
* @return Table descriptors for tables that couldn't be disabled
* @throws IOException
* @see #disableTables(java.util.regex.Pattern)
* @see #disableTable(java.lang.String)
*/
public HTableDescriptor[] disableTables(String regex) throws IOException {
return disableTables(Pattern.compile(regex));
}
/**
* Disable tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and
* {@link #disableTable(byte[])}
*
* @param pattern The pattern to match table names against
* @return Table descriptors for tables that couldn't be disabled
* @throws IOException
*/
public HTableDescriptor[] disableTables(Pattern pattern) throws IOException {
List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
for (HTableDescriptor table : listTables(pattern)) {
if (isTableEnabled(table.getName())) {
try {
disableTable(table.getName());
} catch (IOException ex) {
LOG.info("Failed to disable table " + table.getNameAsString(), ex);
failed.add(table);
}
}
}
return failed.toArray(new HTableDescriptor[failed.size()]);
}
/**
* @param tableName name of table to check
* @return true if table is on-line
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableEnabled(String tableName) throws IOException {
return isTableEnabled(Bytes.toBytes(tableName));
}
/**
* @param tableName name of table to check
* @return true if table is on-line
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableEnabled(byte[] tableName) throws IOException {
if (!HTableDescriptor.isMetaTable(tableName)) {
HTableDescriptor.isLegalTableName(tableName);
}
return connection.isTableEnabled(tableName);
}
/**
* @param tableName name of table to check
* @return true if table is off-line
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableDisabled(final String tableName) throws IOException {
return isTableDisabled(Bytes.toBytes(tableName));
}
/**
* @param tableName name of table to check
* @return true if table is off-line
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableDisabled(byte[] tableName) throws IOException {
if (!HTableDescriptor.isMetaTable(tableName)) {
HTableDescriptor.isLegalTableName(tableName);
}
return connection.isTableDisabled(tableName);
}
/**
* @param tableName name of table to check
* @return true if all regions of the table are available
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableAvailable(byte[] tableName) throws IOException {
return connection.isTableAvailable(tableName);
}
/**
* @param tableName name of table to check
* @return true if all regions of the table are available
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableAvailable(String tableName) throws IOException {
return connection.isTableAvailable(Bytes.toBytes(tableName));
}
/**
* Use this api to check if the table has been created with the specified number of
* splitkeys which was used while creating the given table.
* Note : If this api is used after a table's region gets splitted, the api may return
* false.
* @param tableName
* name of table to check
* @param splitKeys
* keys to check if the table has been created with all split keys
* @throws IOException
* if a remote or network excpetion occurs
*/
public boolean isTableAvailable(String tableName, byte[][] splitKeys) throws IOException {
return connection.isTableAvailable(Bytes.toBytes(tableName), splitKeys);
}
/**
* Use this api to check if the table has been created with the specified number of
* splitkeys which was used while creating the given table.
* Note : If this api is used after a table's region gets splitted, the api may return
* false.
* @param tableName
* name of table to check
* @param splitKeys
* keys to check if the table has been created with all split keys
* @throws IOException
* if a remote or network excpetion occurs
*/
public boolean isTableAvailable(byte[] tableName, byte[][] splitKeys) throws IOException {
return connection.isTableAvailable(tableName, splitKeys);
}
/**
* Get the status of alter command - indicates how many regions have received
* the updated schema Asynchronous operation.
*
* @param tableName
* name of the table to get the status of
* @return Pair indicating the number of regions updated Pair.getFirst() is the
* regions that are yet to be updated Pair.getSecond() is the total number
* of regions of the table
* @throws IOException
* if a remote or network exception occurs
*/
public Pair<Integer, Integer> getAlterStatus(final byte[] tableName)
throws IOException {
HTableDescriptor.isLegalTableName(tableName);
return execute(new MasterMonitorCallable<Pair<Integer, Integer>>() {
@Override
public Pair<Integer, Integer> call() throws ServiceException {
GetSchemaAlterStatusRequest req = RequestConverter
.buildGetSchemaAlterStatusRequest(tableName);
GetSchemaAlterStatusResponse ret = masterMonitor.getSchemaAlterStatus(null, req);
Pair<Integer, Integer> pair = new Pair<Integer, Integer>(Integer.valueOf(ret
.getYetToUpdateRegions()), Integer.valueOf(ret.getTotalRegions()));
return pair;
}
});
}
/**
* Add a column to an existing table.
* Asynchronous operation.
*
* @param tableName name of the table to add column to
* @param column column descriptor of column to be added
* @throws IOException if a remote or network exception occurs
*/
public void addColumn(final String tableName, HColumnDescriptor column)
throws IOException {
addColumn(Bytes.toBytes(tableName), column);
}
/**
* Add a column to an existing table.
* Asynchronous operation.
*
* @param tableName name of the table to add column to
* @param column column descriptor of column to be added
* @throws IOException if a remote or network exception occurs
*/
public void addColumn(final byte [] tableName, final HColumnDescriptor column)
throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
AddColumnRequest req = RequestConverter.buildAddColumnRequest(tableName, column);
masterAdmin.addColumn(null,req);
return null;
}
});
}
/**
* Delete a column from a table.
* Asynchronous operation.
*
* @param tableName name of table
* @param columnName name of column to be deleted
* @throws IOException if a remote or network exception occurs
*/
public void deleteColumn(final String tableName, final String columnName)
throws IOException {
deleteColumn(Bytes.toBytes(tableName), Bytes.toBytes(columnName));
}
/**
* Delete a column from a table.
* Asynchronous operation.
*
* @param tableName name of table
* @param columnName name of column to be deleted
* @throws IOException if a remote or network exception occurs
*/
public void deleteColumn(final byte [] tableName, final byte [] columnName)
throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
DeleteColumnRequest req = RequestConverter.buildDeleteColumnRequest(tableName, columnName);
masterAdmin.deleteColumn(null,req);
return null;
}
});
}
/**
* Modify an existing column family on a table.
* Asynchronous operation.
*
* @param tableName name of table
* @param descriptor new column descriptor to use
* @throws IOException if a remote or network exception occurs
*/
public void modifyColumn(final String tableName, HColumnDescriptor descriptor)
throws IOException {
modifyColumn(Bytes.toBytes(tableName), descriptor);
}
/**
* Modify an existing column family on a table.
* Asynchronous operation.
*
* @param tableName name of table
* @param descriptor new column descriptor to use
* @throws IOException if a remote or network exception occurs
*/
public void modifyColumn(final byte [] tableName, final HColumnDescriptor descriptor)
throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
ModifyColumnRequest req = RequestConverter.buildModifyColumnRequest(tableName, descriptor);
masterAdmin.modifyColumn(null,req);
return null;
}
});
}
/**
* Close a region. For expert-admins. Runs close on the regionserver. The
* master will not be informed of the close.
* @param regionname region name to close
* @param serverName If supplied, we'll use this location rather than
* the one currently in <code>.META.</code>
* @throws IOException if a remote or network exception occurs
*/
public void closeRegion(final String regionname, final String serverName)
throws IOException {
closeRegion(Bytes.toBytes(regionname), serverName);
}
/**
* Close a region. For expert-admins Runs close on the regionserver. The
* master will not be informed of the close.
* @param regionname region name to close
* @param serverName The servername of the regionserver. If passed null we
* will use servername found in the .META. table. A server name
* is made of host, port and startcode. Here is an example:
* <code> host187.example.com,60020,1289493121758</code>
* @throws IOException if a remote or network exception occurs
*/
public void closeRegion(final byte [] regionname, final String serverName)
throws IOException {
CatalogTracker ct = getCatalogTracker();
try {
if (serverName != null) {
Pair<HRegionInfo, ServerName> pair = MetaReader.getRegion(ct, regionname);
if (pair == null || pair.getFirst() == null) {
throw new UnknownRegionException(Bytes.toStringBinary(regionname));
} else {
closeRegion(new ServerName(serverName), pair.getFirst());
}
} else {
Pair<HRegionInfo, ServerName> pair = MetaReader.getRegion(ct, regionname);
if (pair == null) {
throw new UnknownRegionException(Bytes.toStringBinary(regionname));
} else if (pair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(regionname));
} else {
closeRegion(pair.getSecond(), pair.getFirst());
}
}
} finally {
cleanupCatalogTracker(ct);
}
}
/**
* For expert-admins. Runs close on the regionserver. Closes a region based on
* the encoded region name. The region server name is mandatory. If the
* servername is provided then based on the online regions in the specified
* regionserver the specified region will be closed. The master will not be
* informed of the close. Note that the regionname is the encoded regionname.
*
* @param encodedRegionName
* The encoded region name; i.e. the hash that makes up the region
* name suffix: e.g. if regionname is
* <code>TestTable,0094429456,1289497600452.527db22f95c8a9e0116f0cc13c680396.</code>
* , then the encoded region name is:
* <code>527db22f95c8a9e0116f0cc13c680396</code>.
* @param serverName
* The servername of the regionserver. A server name is made of host,
* port and startcode. This is mandatory. Here is an example:
* <code> host187.example.com,60020,1289493121758</code>
* @return true if the region was closed, false if not.
* @throws IOException
* if a remote or network exception occurs
*/
public boolean closeRegionWithEncodedRegionName(final String encodedRegionName,
final String serverName) throws IOException {
if (null == serverName || ("").equals(serverName.trim())) {
throw new IllegalArgumentException(
"The servername cannot be null or empty.");
}
ServerName sn = new ServerName(serverName);
AdminProtocol admin = this.connection.getAdmin(sn);
// Close the region without updating zk state.
CloseRegionRequest request =
RequestConverter.buildCloseRegionRequest(encodedRegionName, false);
try {
CloseRegionResponse response = admin.closeRegion(null, request);
boolean isRegionClosed = response.getClosed();
if (false == isRegionClosed) {
LOG.error("Not able to close the region " + encodedRegionName + ".");
}
return isRegionClosed;
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
/**
* Close a region. For expert-admins Runs close on the regionserver. The
* master will not be informed of the close.
* @param sn
* @param hri
* @throws IOException
*/
public void closeRegion(final ServerName sn, final HRegionInfo hri)
throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
// Close the region without updating zk state.
ProtobufUtil.closeRegion(admin, hri.getRegionName(), false);
}
/**
* Get all the online regions on a region server.
*/
public List<HRegionInfo> getOnlineRegions(
final ServerName sn) throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
return ProtobufUtil.getOnlineRegions(admin);
}
/**
* Flush a table or an individual region.
* Synchronous operation.
*
* @param tableNameOrRegionName table or region to flush
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void flush(final String tableNameOrRegionName)
throws IOException, InterruptedException {
flush(Bytes.toBytes(tableNameOrRegionName));
}
/**
* Flush a table or an individual region.
* Synchronous operation.
*
* @param tableNameOrRegionName table or region to flush
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void flush(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
CatalogTracker ct = getCatalogTracker();
try {
Pair<HRegionInfo, ServerName> regionServerPair
= getRegion(tableNameOrRegionName, ct);
if (regionServerPair != null) {
if (regionServerPair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
} else {
flush(regionServerPair.getSecond(), regionServerPair.getFirst());
}
} else {
final String tableName = tableNameString(tableNameOrRegionName, ct);
List<Pair<HRegionInfo, ServerName>> pairs =
MetaReader.getTableRegionsAndLocations(ct,
tableName);
for (Pair<HRegionInfo, ServerName> pair: pairs) {
if (pair.getFirst().isOffline()) continue;
if (pair.getSecond() == null) continue;
try {
flush(pair.getSecond(), pair.getFirst());
} catch (NotServingRegionException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to flush " + pair.getFirst() + ": " +
StringUtils.stringifyException(e));
}
}
}
}
} finally {
cleanupCatalogTracker(ct);
}
}
private void flush(final ServerName sn, final HRegionInfo hri)
throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
FlushRegionRequest request =
RequestConverter.buildFlushRegionRequest(hri.getRegionName());
try {
admin.flushRegion(null, request);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
/**
* Compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void compact(final String tableNameOrRegionName)
throws IOException, InterruptedException {
compact(Bytes.toBytes(tableNameOrRegionName));
}
/**
* Compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void compact(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
compact(tableNameOrRegionName, null, false);
}
/**
* Compact a column family within a table or region.
* Asynchronous operation.
*
* @param tableOrRegionName table or region to compact
* @param columnFamily column family within a table or region
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void compact(String tableOrRegionName, String columnFamily)
throws IOException, InterruptedException {
compact(Bytes.toBytes(tableOrRegionName), Bytes.toBytes(columnFamily));
}
/**
* Compact a column family within a table or region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to compact
* @param columnFamily column family within a table or region
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void compact(final byte [] tableNameOrRegionName, final byte[] columnFamily)
throws IOException, InterruptedException {
compact(tableNameOrRegionName, columnFamily, false);
}
/**
* Major compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to major compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void majorCompact(final String tableNameOrRegionName)
throws IOException, InterruptedException {
majorCompact(Bytes.toBytes(tableNameOrRegionName));
}
/**
* Major compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to major compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void majorCompact(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
compact(tableNameOrRegionName, null, true);
}
/**
* Major compact a column family within a table or region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to major compact
* @param columnFamily column family within a table or region
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void majorCompact(final String tableNameOrRegionName,
final String columnFamily) throws IOException, InterruptedException {
majorCompact(Bytes.toBytes(tableNameOrRegionName),
Bytes.toBytes(columnFamily));
}
/**
* Major compact a column family within a table or region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to major compact
* @param columnFamily column family within a table or region
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void majorCompact(final byte [] tableNameOrRegionName,
final byte[] columnFamily) throws IOException, InterruptedException {
compact(tableNameOrRegionName, columnFamily, true);
}
/**
* Compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to compact
* @param columnFamily column family within a table or region
* @param major True if we are to do a major compaction.
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
private void compact(final byte [] tableNameOrRegionName,
final byte[] columnFamily,final boolean major)
throws IOException, InterruptedException {
CatalogTracker ct = getCatalogTracker();
try {
Pair<HRegionInfo, ServerName> regionServerPair
= getRegion(tableNameOrRegionName, ct);
if (regionServerPair != null) {
if (regionServerPair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
} else {
compact(regionServerPair.getSecond(), regionServerPair.getFirst(), major, columnFamily);
}
} else {
final String tableName = tableNameString(tableNameOrRegionName, ct);
List<Pair<HRegionInfo, ServerName>> pairs =
MetaReader.getTableRegionsAndLocations(ct,
tableName);
for (Pair<HRegionInfo, ServerName> pair: pairs) {
if (pair.getFirst().isOffline()) continue;
if (pair.getSecond() == null) continue;
try {
compact(pair.getSecond(), pair.getFirst(), major, columnFamily);
} catch (NotServingRegionException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to" + (major ? " major" : "") + " compact " +
pair.getFirst() + ": " +
StringUtils.stringifyException(e));
}
}
}
}
} finally {
cleanupCatalogTracker(ct);
}
}
private void compact(final ServerName sn, final HRegionInfo hri,
final boolean major, final byte [] family)
throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
CompactRegionRequest request =
RequestConverter.buildCompactRegionRequest(hri.getRegionName(), major, family);
try {
admin.compactRegion(null, request);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
/**
* Move the region <code>r</code> to <code>dest</code>.
* @param encodedRegionName The encoded region name; i.e. the hash that makes
* up the region name suffix: e.g. if regionname is
* <code>TestTable,0094429456,1289497600452.527db22f95c8a9e0116f0cc13c680396.</code>,
* then the encoded region name is: <code>527db22f95c8a9e0116f0cc13c680396</code>.
* @param destServerName The servername of the destination regionserver. If
* passed the empty byte array we'll assign to a random server. A server name
* is made of host, port and startcode. Here is an example:
* <code> host187.example.com,60020,1289493121758</code>
* @throws UnknownRegionException Thrown if we can't find a region named
* <code>encodedRegionName</code>
* @throws ZooKeeperConnectionException
* @throws MasterNotRunningException
*/
public void move(final byte [] encodedRegionName, final byte [] destServerName)
throws UnknownRegionException, MasterNotRunningException, ZooKeeperConnectionException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
MoveRegionRequest request = RequestConverter.buildMoveRegionRequest(encodedRegionName, destServerName);
master.moveRegion(null,request);
} catch (ServiceException se) {
IOException ioe = ProtobufUtil.getRemoteException(se);
if (ioe instanceof UnknownRegionException) {
throw (UnknownRegionException)ioe;
}
LOG.error("Unexpected exception: " + se + " from calling HMaster.moveRegion");
} catch (DeserializationException de) {
LOG.error("Could not parse destination server name: " + de);
}
finally {
master.close();
}
}
/**
* @param regionName
* Region name to assign.
* @throws MasterNotRunningException
* @throws ZooKeeperConnectionException
* @throws IOException
*/
public void assign(final byte[] regionName) throws MasterNotRunningException,
ZooKeeperConnectionException, IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
AssignRegionRequest request = RequestConverter.buildAssignRegionRequest(regionName);
masterAdmin.assignRegion(null,request);
return null;
}
});
}
/**
* Unassign a region from current hosting regionserver. Region will then be
* assigned to a regionserver chosen at random. Region could be reassigned
* back to the same server. Use {@link #move(byte[], byte[])} if you want
* to control the region movement.
* @param regionName Region to unassign. Will clear any existing RegionPlan
* if one found.
* @param force If true, force unassign (Will remove region from
* regions-in-transition too if present. If results in double assignment
* use hbck -fix to resolve. To be used by experts).
* @throws MasterNotRunningException
* @throws ZooKeeperConnectionException
* @throws IOException
*/
public void unassign(final byte [] regionName, final boolean force)
throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
UnassignRegionRequest request =
RequestConverter.buildUnassignRegionRequest(regionName, force);
masterAdmin.unassignRegion(null,request);
return null;
}
});
}
/**
* Special method, only used by hbck.
*/
public void offline(final byte [] regionName)
throws IOException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
master.offlineRegion(null,RequestConverter.buildOfflineRegionRequest(regionName));
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
} finally {
master.close();
}
}
/**
* Turn the load balancer on or off.
* @param on If true, enable balancer. If false, disable balancer.
* @param synchronous If true, it waits until current balance() call, if outstanding, to return.
* @return Previous balancer value
*/
public boolean setBalancerRunning(final boolean on, final boolean synchronous)
throws MasterNotRunningException, ZooKeeperConnectionException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
SetBalancerRunningRequest req =
RequestConverter.buildSetBalancerRunningRequest(on, synchronous);
return master.setBalancerRunning(null, req).getPrevBalanceValue();
} catch (ServiceException se) {
IOException ioe = ProtobufUtil.getRemoteException(se);
if (ioe instanceof MasterNotRunningException) {
throw (MasterNotRunningException)ioe;
}
if (ioe instanceof ZooKeeperConnectionException) {
throw (ZooKeeperConnectionException)ioe;
}
// Throwing MasterNotRunningException even though not really valid in order to not
// break interface by adding additional exception type.
throw new MasterNotRunningException("Unexpected exception when calling balanceSwitch",se);
} finally {
master.close();
}
}
/**
* Invoke the balancer. Will run the balancer and if regions to move, it will
* go ahead and do the reassignments. Can NOT run for various reasons. Check
* logs.
* @return True if balancer ran, false otherwise.
*/
public boolean balancer()
throws MasterNotRunningException, ZooKeeperConnectionException, ServiceException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
return master.balance(null,RequestConverter.buildBalanceRequest()).getBalancerRan();
} finally {
master.close();
}
}
/**
* Enable/Disable the catalog janitor
* @param enable if true enables the catalog janitor
* @return the previous state
* @throws ServiceException
* @throws MasterNotRunningException
*/
public boolean enableCatalogJanitor(boolean enable)
throws ServiceException, MasterNotRunningException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
return master.enableCatalogJanitor(null,
RequestConverter.buildEnableCatalogJanitorRequest(enable)).getPrevValue();
} finally {
master.close();
}
}
/**
* Ask for a scan of the catalog table
* @return the number of entries cleaned
* @throws ServiceException
* @throws MasterNotRunningException
*/
public int runCatalogScan() throws ServiceException, MasterNotRunningException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
return master.runCatalogScan(null,
RequestConverter.buildCatalogScanRequest()).getScanResult();
} finally {
master.close();
}
}
/**
* Query on the catalog janitor state (Enabled/Disabled?)
* @throws ServiceException
* @throws org.apache.hadoop.hbase.exceptions.MasterNotRunningException
*/
public boolean isCatalogJanitorEnabled() throws ServiceException, MasterNotRunningException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
return master.isCatalogJanitorEnabled(null,
RequestConverter.buildIsCatalogJanitorEnabledRequest()).getValue();
} finally {
master.close();
}
}
/**
* Split a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to split
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void split(final String tableNameOrRegionName)
throws IOException, InterruptedException {
split(Bytes.toBytes(tableNameOrRegionName));
}
/**
* Split a table or an individual region. Implicitly finds an optimal split
* point. Asynchronous operation.
*
* @param tableNameOrRegionName table to region to split
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void split(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
split(tableNameOrRegionName, null);
}
public void split(final String tableNameOrRegionName,
final String splitPoint) throws IOException, InterruptedException {
split(Bytes.toBytes(tableNameOrRegionName), Bytes.toBytes(splitPoint));
}
/**
* Split a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table to region to split
* @param splitPoint the explicit position to split on
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException interrupt exception occurred
*/
public void split(final byte [] tableNameOrRegionName,
final byte [] splitPoint) throws IOException, InterruptedException {
CatalogTracker ct = getCatalogTracker();
try {
Pair<HRegionInfo, ServerName> regionServerPair
= getRegion(tableNameOrRegionName, ct);
if (regionServerPair != null) {
if (regionServerPair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
} else {
split(regionServerPair.getSecond(), regionServerPair.getFirst(), splitPoint);
}
} else {
final String tableName = tableNameString(tableNameOrRegionName, ct);
List<Pair<HRegionInfo, ServerName>> pairs =
MetaReader.getTableRegionsAndLocations(ct,
tableName);
for (Pair<HRegionInfo, ServerName> pair: pairs) {
// May not be a server for a particular row
if (pair.getSecond() == null) continue;
HRegionInfo r = pair.getFirst();
// check for parents
if (r.isSplitParent()) continue;
// if a split point given, only split that particular region
if (splitPoint != null && !r.containsRow(splitPoint)) continue;
// call out to region server to do split now
split(pair.getSecond(), pair.getFirst(), splitPoint);
}
}
} finally {
cleanupCatalogTracker(ct);
}
}
private void split(final ServerName sn, final HRegionInfo hri,
byte[] splitPoint) throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
ProtobufUtil.split(admin, hri, splitPoint);
}
/**
* Modify an existing table, more IRB friendly version.
* Asynchronous operation. This means that it may be a while before your
* schema change is updated across all of the table.
*
* @param tableName name of table.
* @param htd modified description of the table
* @throws IOException if a remote or network exception occurs
*/
public void modifyTable(final byte [] tableName, final HTableDescriptor htd)
throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
ModifyTableRequest request = RequestConverter.buildModifyTableRequest(tableName, htd);
masterAdmin.modifyTable(null, request);
return null;
}
});
}
/**
* @param tableNameOrRegionName Name of a table or name of a region.
* @param ct A {@link CatalogTracker} instance (caller of this method usually has one).
* @return a pair of HRegionInfo and ServerName if <code>tableNameOrRegionName</code> is
* a verified region name (we call {@link MetaReader#getRegion( CatalogTracker, byte[])}
* else null.
* Throw an exception if <code>tableNameOrRegionName</code> is null.
* @throws IOException
*/
Pair<HRegionInfo, ServerName> getRegion(final byte[] tableNameOrRegionName,
final CatalogTracker ct) throws IOException {
if (tableNameOrRegionName == null) {
throw new IllegalArgumentException("Pass a table name or region name");
}
Pair<HRegionInfo, ServerName> pair = MetaReader.getRegion(ct, tableNameOrRegionName);
if (pair == null) {
final AtomicReference<Pair<HRegionInfo, ServerName>> result =
new AtomicReference<Pair<HRegionInfo, ServerName>>(null);
final String encodedName = Bytes.toString(tableNameOrRegionName);
MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
@Override
public boolean processRow(Result data) throws IOException {
HRegionInfo info = HRegionInfo.getHRegionInfo(data);
if (info == null) {
LOG.warn("No serialized HRegionInfo in " + data);
return true;
}
if (!encodedName.equals(info.getEncodedName())) return true;
ServerName sn = HRegionInfo.getServerName(data);
result.set(new Pair<HRegionInfo, ServerName>(info, sn));
return false; // found the region, stop
}
};
MetaScanner.metaScan(conf, visitor);
pair = result.get();
}
return pair;
}
/**
* Convert the table name byte array into a table name string and check if table
* exists or not.
* @param tableNameBytes Name of a table.
* @param ct A {@link CatalogTracker} instance (caller of this method usually has one).
* @return tableName in string form.
* @throws IOException if a remote or network exception occurs.
* @throws TableNotFoundException if table does not exist.
*/
private String tableNameString(final byte[] tableNameBytes, CatalogTracker ct)
throws IOException {
String tableNameString = Bytes.toString(tableNameBytes);
if (!MetaReader.tableExists(ct, tableNameString)) {
throw new TableNotFoundException(tableNameString);
}
return tableNameString;
}
/**
* Shuts down the HBase cluster
* @throws IOException if a remote or network exception occurs
*/
public synchronized void shutdown() throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
masterAdmin.shutdown(null,ShutdownRequest.newBuilder().build());
return null;
}
});
}
/**
* Shuts down the current HBase master only.
* Does not shutdown the cluster.
* @see #shutdown()
* @throws IOException if a remote or network exception occurs
*/
public synchronized void stopMaster() throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
masterAdmin.stopMaster(null,StopMasterRequest.newBuilder().build());
return null;
}
});
}
/**
* Stop the designated regionserver
* @param hostnamePort Hostname and port delimited by a <code>:</code> as in
* <code>example.org:1234</code>
* @throws IOException if a remote or network exception occurs
*/
public synchronized void stopRegionServer(final String hostnamePort)
throws IOException {
String hostname = Addressing.parseHostname(hostnamePort);
int port = Addressing.parsePort(hostnamePort);
AdminProtocol admin =
this.connection.getAdmin(new ServerName(hostname, port, 0));
StopServerRequest request = RequestConverter.buildStopServerRequest(
"Called by admin client " + this.connection.toString());
try {
admin.stopServer(null, request);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
/**
* @return cluster status
* @throws IOException if a remote or network exception occurs
*/
public ClusterStatus getClusterStatus() throws IOException {
return execute(new MasterMonitorCallable<ClusterStatus>() {
@Override
public ClusterStatus call() throws ServiceException {
GetClusterStatusRequest req = RequestConverter.buildGetClusterStatusRequest();
return ClusterStatus.convert(masterMonitor.getClusterStatus(null,req).getClusterStatus());
}
});
}
private HRegionLocation getFirstMetaServerForTable(final byte [] tableName)
throws IOException {
return connection.locateRegion(HConstants.META_TABLE_NAME,
HRegionInfo.createRegionName(tableName, null, HConstants.NINES, false));
}
/**
* @return Configuration used by the instance.
*/
public Configuration getConfiguration() {
return this.conf;
}
/**
* Check to see if HBase is running. Throw an exception if not.
* We consider that HBase is running if ZooKeeper and Master are running.
*
* @param conf system configuration
* @throws MasterNotRunningException if the master is not running
* @throws ZooKeeperConnectionException if unable to connect to zookeeper
*/
public static void checkHBaseAvailable(Configuration conf)
throws MasterNotRunningException, ZooKeeperConnectionException, ServiceException {
Configuration copyOfConf = HBaseConfiguration.create(conf);
// We set it to make it fail as soon as possible if HBase is not available
copyOfConf.setInt("hbase.client.retries.number", 1);
copyOfConf.setInt("zookeeper.recovery.retry", 0);
HConnectionManager.HConnectionImplementation connection
= (HConnectionManager.HConnectionImplementation)
HConnectionManager.getConnection(copyOfConf);
try {
// Check ZK first.
// If the connection exists, we may have a connection to ZK that does
// not work anymore
ZooKeeperKeepAliveConnection zkw = null;
try {
zkw = connection.getKeepAliveZooKeeperWatcher();
zkw.getRecoverableZooKeeper().getZooKeeper().exists(
zkw.baseZNode, false);
} catch (IOException e) {
throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
} catch (KeeperException e) {
throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
} finally {
if (zkw != null) {
zkw.close();
}
}
// Check Master
connection.isMasterRunning();
} finally {
connection.close();
}
}
/**
* get the regions of a given table.
*
* @param tableName the name of the table
* @return Ordered list of {@link HRegionInfo}.
* @throws IOException
*/
public List<HRegionInfo> getTableRegions(final byte[] tableName)
throws IOException {
CatalogTracker ct = getCatalogTracker();
List<HRegionInfo> Regions = null;
try {
Regions = MetaReader.getTableRegions(ct, tableName, true);
} finally {
cleanupCatalogTracker(ct);
}
return Regions;
}
@Override
public void close() throws IOException {
if (this.connection != null) {
this.connection.close();
}
}
/**
* Get tableDescriptors
* @param tableNames List of table names
* @return HTD[] the tableDescriptor
* @throws IOException if a remote or network exception occurs
*/
public HTableDescriptor[] getTableDescriptors(List<String> tableNames)
throws IOException {
return this.connection.getHTableDescriptors(tableNames);
}
/**
* Roll the log writer. That is, start writing log messages to a new file.
*
* @param serverName
* The servername of the regionserver. A server name is made of host,
* port and startcode. This is mandatory. Here is an example:
* <code> host187.example.com,60020,1289493121758</code>
* @return If lots of logs, flush the returned regions so next time through
* we can clean logs. Returns null if nothing to flush. Names are actual
* region names as returned by {@link HRegionInfo#getEncodedName()}
* @throws IOException if a remote or network exception occurs
* @throws FailedLogCloseException
*/
public synchronized byte[][] rollHLogWriter(String serverName)
throws IOException, FailedLogCloseException {
ServerName sn = new ServerName(serverName);
AdminProtocol admin = this.connection.getAdmin(sn);
RollWALWriterRequest request = RequestConverter.buildRollWALWriterRequest();
try {
RollWALWriterResponse response = admin.rollWALWriter(null, request);
int regionCount = response.getRegionToFlushCount();
byte[][] regionsToFlush = new byte[regionCount][];
for (int i = 0; i < regionCount; i++) {
ByteString region = response.getRegionToFlush(i);
regionsToFlush[i] = region.toByteArray();
}
return regionsToFlush;
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
public String[] getMasterCoprocessors() {
try {
return getClusterStatus().getMasterCoprocessors();
} catch (IOException e) {
LOG.error("Could not getClusterStatus()",e);
return null;
}
}
/**
* Get the current compaction state of a table or region.
* It could be in a major compaction, a minor compaction, both, or none.
*
* @param tableNameOrRegionName table or region to major compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
* @return the current compaction state
*/
public CompactionState getCompactionState(final String tableNameOrRegionName)
throws IOException, InterruptedException {
return getCompactionState(Bytes.toBytes(tableNameOrRegionName));
}
/**
* Get the current compaction state of a table or region.
* It could be in a major compaction, a minor compaction, both, or none.
*
* @param tableNameOrRegionName table or region to major compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
* @return the current compaction state
*/
public CompactionState getCompactionState(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
CompactionState state = CompactionState.NONE;
CatalogTracker ct = getCatalogTracker();
try {
Pair<HRegionInfo, ServerName> regionServerPair
= getRegion(tableNameOrRegionName, ct);
if (regionServerPair != null) {
if (regionServerPair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
} else {
ServerName sn = regionServerPair.getSecond();
AdminProtocol admin =
this.connection.getAdmin(sn);
GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
regionServerPair.getFirst().getRegionName(), true);
GetRegionInfoResponse response = admin.getRegionInfo(null, request);
return response.getCompactionState();
}
} else {
final String tableName = tableNameString(tableNameOrRegionName, ct);
List<Pair<HRegionInfo, ServerName>> pairs =
MetaReader.getTableRegionsAndLocations(ct, tableName);
for (Pair<HRegionInfo, ServerName> pair: pairs) {
if (pair.getFirst().isOffline()) continue;
if (pair.getSecond() == null) continue;
try {
ServerName sn = pair.getSecond();
AdminProtocol admin =
this.connection.getAdmin(sn);
GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
pair.getFirst().getRegionName(), true);
GetRegionInfoResponse response = admin.getRegionInfo(null, request);
switch (response.getCompactionState()) {
case MAJOR_AND_MINOR:
return CompactionState.MAJOR_AND_MINOR;
case MAJOR:
if (state == CompactionState.MINOR) {
return CompactionState.MAJOR_AND_MINOR;
}
state = CompactionState.MAJOR;
break;
case MINOR:
if (state == CompactionState.MAJOR) {
return CompactionState.MAJOR_AND_MINOR;
}
state = CompactionState.MINOR;
break;
case NONE:
default: // nothing, continue
}
} catch (NotServingRegionException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to get compaction state of " +
pair.getFirst() + ": " +
StringUtils.stringifyException(e));
}
}
}
}
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
} finally {
cleanupCatalogTracker(ct);
}
return state;
}
/**
* Take a snapshot for the given table. If the table is enabled, a FLUSH-type snapshot will be
* taken. If the table is disabled, an offline snapshot is taken.
* <p>
* Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
* snapshot with the same name (even a different type or with different parameters) will fail with
* a {@link SnapshotCreationException} indicating the duplicate naming.
* <p>
* Snapshot names follow the same naming constraints as tables in HBase. See
* {@link HTableDescriptor#isLegalTableName(byte[])}.
* @param snapshotName name of the snapshot to be created
* @param tableName name of the table for which snapshot is created
* @throws IOException if a remote or network exception occurs
* @throws SnapshotCreationException if snapshot creation failed
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public void snapshot(final String snapshotName, final String tableName) throws IOException,
SnapshotCreationException, IllegalArgumentException {
snapshot(snapshotName, tableName, SnapshotDescription.Type.FLUSH);
}
/**
* Create a timestamp consistent snapshot for the given table.
* <p>
* Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
* snapshot with the same name (even a different type or with different parameters) will fail with
* a {@link SnapshotCreationException} indicating the duplicate naming.
* <p>
* Snapshot names follow the same naming constraints as tables in HBase. See
* {@link HTableDescriptor#isLegalTableName(byte[])}.
* @param snapshotName name of the snapshot to be created
* @param tableName name of the table for which snapshot is created
* @throws IOException if a remote or network exception occurs
* @throws SnapshotCreationException if snapshot creation failed
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public void snapshot(final byte[] snapshotName, final byte[] tableName) throws IOException,
SnapshotCreationException, IllegalArgumentException {
snapshot(Bytes.toString(snapshotName), Bytes.toString(tableName));
}
/**
* Create typed snapshot of the table.
* <p>
* Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
* snapshot with the same name (even a different type or with different parameters) will fail with
* a {@link SnapshotCreationException} indicating the duplicate naming.
* <p>
* Snapshot names follow the same naming constraints as tables in HBase. See
* {@link HTableDescriptor#isLegalTableName(byte[])}.
* <p>
* @param snapshotName name to give the snapshot on the filesystem. Must be unique from all other
* snapshots stored on the cluster
* @param tableName name of the table to snapshot
* @param type type of snapshot to take
* @throws IOException we fail to reach the master
* @throws SnapshotCreationException if snapshot creation failed
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public void snapshot(final String snapshotName, final String tableName,
SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
IllegalArgumentException {
SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
builder.setTable(tableName);
builder.setName(snapshotName);
builder.setType(type);
snapshot(builder.build());
}
/**
* Take a snapshot and wait for the server to complete that snapshot (blocking).
* <p>
* Only a single snapshot should be taken at a time for an instance of HBase, or results may be
* undefined (you can tell multiple HBase clusters to snapshot at the same time, but only one at a
* time for a single cluster).
* <p>
* Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
* snapshot with the same name (even a different type or with different parameters) will fail with
* a {@link SnapshotCreationException} indicating the duplicate naming.
* <p>
* Snapshot names follow the same naming constraints as tables in HBase. See
* {@link HTableDescriptor#isLegalTableName(byte[])}.
* <p>
* You should probably use {@link #snapshot(String, String)} or {@link #snapshot(byte[], byte[])}
* unless you are sure about the type of snapshot that you want to take.
* @param snapshot snapshot to take
* @throws IOException or we lose contact with the master.
* @throws SnapshotCreationException if snapshot failed to be taken
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public void snapshot(SnapshotDescription snapshot) throws IOException, SnapshotCreationException,
IllegalArgumentException {
// actually take the snapshot
TakeSnapshotResponse response = takeSnapshotAsync(snapshot);
final IsSnapshotDoneRequest request = IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot)
.build();
IsSnapshotDoneResponse done = null;
long start = EnvironmentEdgeManager.currentTimeMillis();
long max = response.getExpectedTimeout();
long maxPauseTime = max / this.numRetries;
int tries = 0;
LOG.debug("Waiting a max of " + max + " ms for snapshot '" +
ClientSnapshotDescriptionUtils.toString(snapshot) + "'' to complete. (max " +
maxPauseTime + " ms per retry)");
while (tries == 0
|| ((EnvironmentEdgeManager.currentTimeMillis() - start) < max && !done.getDone())) {
try {
// sleep a backoff <= pauseTime amount
long sleep = getPauseTime(tries++);
sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
LOG.debug("(#" + tries + ") Sleeping: " + sleep +
"ms while waiting for snapshot completion.");
Thread.sleep(sleep);
} catch (InterruptedException e) {
LOG.debug("Interrupted while waiting for snapshot " + snapshot + " to complete");
Thread.currentThread().interrupt();
}
LOG.debug("Getting current status of snapshot from master...");
done = execute(new MasterAdminCallable<IsSnapshotDoneResponse>() {
@Override
public IsSnapshotDoneResponse call() throws ServiceException {
return masterAdmin.isSnapshotDone(null, request);
}
});
};
if (!done.getDone()) {
throw new SnapshotCreationException("Snapshot '" + snapshot.getName()
+ "' wasn't completed in expectedTime:" + max + " ms", snapshot);
}
}
/**
* Take a snapshot without waiting for the server to complete that snapshot (asynchronous)
* <p>
* Only a single snapshot should be taken at a time, or results may be undefined.
* @param snapshot snapshot to take
* @return response from the server indicating the max time to wait for the snapshot
* @throws IOException if the snapshot did not succeed or we lose contact with the master.
* @throws SnapshotCreationException if snapshot creation failed
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public TakeSnapshotResponse takeSnapshotAsync(SnapshotDescription snapshot) throws IOException,
SnapshotCreationException {
ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
final TakeSnapshotRequest request = TakeSnapshotRequest.newBuilder().setSnapshot(snapshot)
.build();
// run the snapshot on the master
return execute(new MasterAdminCallable<TakeSnapshotResponse>() {
@Override
public TakeSnapshotResponse call() throws ServiceException {
return masterAdmin.snapshot(null, request);
}
});
}
/**
* Check the current state of the passed snapshot.
* <p>
* There are three possible states:
* <ol>
* <li>running - returns <tt>false</tt></li>
* <li>finished - returns <tt>true</tt></li>
* <li>finished with error - throws the exception that caused the snapshot to fail</li>
* </ol>
* <p>
* The cluster only knows about the most recent snapshot. Therefore, if another snapshot has been
* run/started since the snapshot your are checking, you will recieve an
* {@link UnknownSnapshotException}.
* @param snapshot description of the snapshot to check
* @return <tt>true</tt> if the snapshot is completed, <tt>false</tt> if the snapshot is still
* running
* @throws IOException if we have a network issue
* @throws HBaseSnapshotException if the snapshot failed
* @throws UnknownSnapshotException if the requested snapshot is unknown
*/
public boolean isSnapshotFinished(final SnapshotDescription snapshot)
throws IOException, HBaseSnapshotException, UnknownSnapshotException {
return execute(new MasterAdminCallable<IsSnapshotDoneResponse>() {
@Override
public IsSnapshotDoneResponse call() throws ServiceException {
return masterAdmin.isSnapshotDone(null,
IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot).build());
}
}).getDone();
}
/**
* Restore the specified snapshot on the original table. (The table must be disabled)
* Before restoring the table, a new snapshot with the current table state is created.
* In case of failure, the table will be rolled back to its original state.
*
* @param snapshotName name of the snapshot to restore
* @throws IOException if a remote or network exception occurs
* @throws RestoreSnapshotException if snapshot failed to be restored
* @throws IllegalArgumentException if the restore request is formatted incorrectly
*/
public void restoreSnapshot(final byte[] snapshotName)
throws IOException, RestoreSnapshotException {
restoreSnapshot(Bytes.toString(snapshotName));
}
/**
* Restore the specified snapshot on the original table. (The table must be disabled)
* Before restoring the table, a new snapshot with the current table state is created.
* In case of failure, the table will be rolled back to the its original state.
*
* @param snapshotName name of the snapshot to restore
* @throws IOException if a remote or network exception occurs
* @throws RestoreSnapshotException if snapshot failed to be restored
* @throws IllegalArgumentException if the restore request is formatted incorrectly
*/
public void restoreSnapshot(final String snapshotName)
throws IOException, RestoreSnapshotException {
String rollbackSnapshot = snapshotName + "-" + EnvironmentEdgeManager.currentTimeMillis();
String tableName = null;
for (SnapshotDescription snapshotInfo: listSnapshots()) {
if (snapshotInfo.getName().equals(snapshotName)) {
tableName = snapshotInfo.getTable();
break;
}
}
if (tableName == null) {
throw new RestoreSnapshotException(
"Unable to find the table name for snapshot=" + snapshotName);
}
// Take a snapshot of the current state
snapshot(rollbackSnapshot, tableName);
// Restore snapshot
try {
internalRestoreSnapshot(snapshotName, tableName);
} catch (IOException e) {
// Try to rollback
try {
String msg = "Restore snapshot=" + snapshotName +
" failed. Rollback to snapshot=" + rollbackSnapshot + " succeeded.";
LOG.error(msg, e);
internalRestoreSnapshot(rollbackSnapshot, tableName);
throw new RestoreSnapshotException(msg, e);
} catch (IOException ex) {
String msg = "Failed to restore and rollback to snapshot=" + rollbackSnapshot;
LOG.error(msg, ex);
throw new RestoreSnapshotException(msg, ex);
}
}
}
/**
* Create a new table by cloning the snapshot content.
*
* @param snapshotName name of the snapshot to be cloned
* @param tableName name of the table where the snapshot will be restored
* @throws IOException if a remote or network exception occurs
* @throws TableExistsException if table to be created already exists
* @throws RestoreSnapshotException if snapshot failed to be cloned
* @throws IllegalArgumentException if the specified table has not a valid name
*/
public void cloneSnapshot(final byte[] snapshotName, final byte[] tableName)
throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
cloneSnapshot(Bytes.toString(snapshotName), Bytes.toString(tableName));
}
/**
* Create a new table by cloning the snapshot content.
*
* @param snapshotName name of the snapshot to be cloned
* @param tableName name of the table where the snapshot will be restored
* @throws IOException if a remote or network exception occurs
* @throws TableExistsException if table to be created already exists
* @throws RestoreSnapshotException if snapshot failed to be cloned
* @throws IllegalArgumentException if the specified table has not a valid name
*/
public void cloneSnapshot(final String snapshotName, final String tableName)
throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
if (tableExists(tableName)) {
throw new TableExistsException("Table '" + tableName + " already exists");
}
internalRestoreSnapshot(snapshotName, tableName);
waitUntilTableIsEnabled(Bytes.toBytes(tableName));
}
/**
* Execute Restore/Clone snapshot and wait for the server to complete (blocking).
* To check if the cloned table exists, use {@link #isTableAvailable} -- it is not safe to
* create an HTable instance to this table before it is available.
* @param snapshot snapshot to restore
* @param tableName table name to restore the snapshot on
* @throws IOException if a remote or network exception occurs
* @throws RestoreSnapshotException if snapshot failed to be restored
* @throws IllegalArgumentException if the restore request is formatted incorrectly
*/
private void internalRestoreSnapshot(final String snapshotName, final String tableName)
throws IOException, RestoreSnapshotException {
SnapshotDescription snapshot = SnapshotDescription.newBuilder()
.setName(snapshotName).setTable(tableName).build();
// actually restore the snapshot
internalRestoreSnapshotAsync(snapshot);
final IsRestoreSnapshotDoneRequest request = IsRestoreSnapshotDoneRequest.newBuilder()
.setSnapshot(snapshot).build();
IsRestoreSnapshotDoneResponse done = IsRestoreSnapshotDoneResponse.newBuilder().buildPartial();
final long maxPauseTime = 5000;
int tries = 0;
while (!done.getDone()) {
try {
// sleep a backoff <= pauseTime amount
long sleep = getPauseTime(tries++);
sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
LOG.debug(tries + ") Sleeping: " + sleep + " ms while we wait for snapshot restore to complete.");
Thread.sleep(sleep);
} catch (InterruptedException e) {
LOG.debug("Interrupted while waiting for snapshot " + snapshot + " restore to complete");
Thread.currentThread().interrupt();
}
LOG.debug("Getting current status of snapshot restore from master...");
done = execute(new MasterAdminCallable<IsRestoreSnapshotDoneResponse>() {
@Override
public IsRestoreSnapshotDoneResponse call() throws ServiceException {
return masterAdmin.isRestoreSnapshotDone(null, request);
}
});
}
if (!done.getDone()) {
throw new RestoreSnapshotException("Snapshot '" + snapshot.getName() + "' wasn't restored.");
}
}
/**
* Execute Restore/Clone snapshot and wait for the server to complete (asynchronous)
* <p>
* Only a single snapshot should be restored at a time, or results may be undefined.
* @param snapshot snapshot to restore
* @return response from the server indicating the max time to wait for the snapshot
* @throws IOException if a remote or network exception occurs
* @throws RestoreSnapshotException if snapshot failed to be restored
* @throws IllegalArgumentException if the restore request is formatted incorrectly
*/
private RestoreSnapshotResponse internalRestoreSnapshotAsync(final SnapshotDescription snapshot)
throws IOException, RestoreSnapshotException {
ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
final RestoreSnapshotRequest request = RestoreSnapshotRequest.newBuilder().setSnapshot(snapshot)
.build();
// run the snapshot restore on the master
return execute(new MasterAdminCallable<RestoreSnapshotResponse>() {
@Override
public RestoreSnapshotResponse call() throws ServiceException {
return masterAdmin.restoreSnapshot(null, request);
}
});
}
/**
* List completed snapshots.
* @return a list of snapshot descriptors for completed snapshots
* @throws IOException if a network error occurs
*/
public List<SnapshotDescription> listSnapshots() throws IOException {
return execute(new MasterAdminCallable<List<SnapshotDescription>>() {
@Override
public List<SnapshotDescription> call() throws ServiceException {
return masterAdmin.getCompletedSnapshots(null, ListSnapshotRequest.newBuilder().build())
.getSnapshotsList();
}
});
}
/**
* Delete an existing snapshot.
* @param snapshotName name of the snapshot
* @throws IOException if a remote or network exception occurs
*/
public void deleteSnapshot(final byte[] snapshotName) throws IOException {
deleteSnapshot(Bytes.toString(snapshotName));
}
/**
* Delete an existing snapshot.
* @param snapshotName name of the snapshot
* @throws IOException if a remote or network exception occurs
*/
public void deleteSnapshot(final String snapshotName) throws IOException {
// make sure the snapshot is possibly valid
HTableDescriptor.isLegalTableName(Bytes.toBytes(snapshotName));
// do the delete
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
masterAdmin.deleteSnapshot(
null,
DeleteSnapshotRequest.newBuilder()
.setSnapshot(SnapshotDescription.newBuilder().setName(snapshotName).build()).build());
return null;
}
});
}
/**
* @see {@link #execute(MasterAdminCallable<V>)}
*/
private abstract static class MasterAdminCallable<V> implements Callable<V>{
protected MasterAdminKeepAliveConnection masterAdmin;
}
/**
* @see {@link #execute(MasterMonitorCallable<V>)}
*/
private abstract static class MasterMonitorCallable<V> implements Callable<V> {
protected MasterMonitorKeepAliveConnection masterMonitor;
}
/**
* This method allows to execute a function requiring a connection to
* master without having to manage the connection creation/close.
* Create a {@link MasterAdminCallable} to use it.
*/
private <V> V execute(MasterAdminCallable<V> function) throws IOException {
function.masterAdmin = connection.getKeepAliveMasterAdmin();
try {
return executeCallable(function);
} finally {
function.masterAdmin.close();
}
}
/**
* This method allows to execute a function requiring a connection to
* master without having to manage the connection creation/close.
* Create a {@link MasterAdminCallable} to use it.
*/
private <V> V execute(MasterMonitorCallable<V> function) throws IOException {
function.masterMonitor = connection.getKeepAliveMasterMonitor();
try {
return executeCallable(function);
} finally {
function.masterMonitor.close();
}
}
/**
* Helper function called by other execute functions.
*/
private <V> V executeCallable(Callable<V> function) throws IOException {
try {
return function.call();
} catch (RemoteException re) {
throw re.unwrapRemoteException();
} catch (IOException e) {
throw e;
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
} catch (Exception e) {
// This should not happen...
throw new IOException("Unexpected exception when calling master", e);
}
}
/**
* Creates and returns a {@link com.google.protobuf.RpcChannel} instance
* connected to the active master.
*
* <p>
* The obtained {@link com.google.protobuf.RpcChannel} instance can be used to access a published
* coprocessor {@link com.google.protobuf.Service} using standard protobuf service invocations:
* </p>
*
* <div style="background-color: #cccccc; padding: 2px">
* <blockquote><pre>
* CoprocessorRpcChannel channel = myAdmin.coprocessorService();
* MyService.BlockingInterface service = MyService.newBlockingStub(channel);
* MyCallRequest request = MyCallRequest.newBuilder()
* ...
* .build();
* MyCallResponse response = service.myCall(null, request);
* </pre></blockquote></div>
*
* @return A MasterCoprocessorRpcChannel instance
*/
public CoprocessorRpcChannel coprocessorService() {
return new MasterCoprocessorRpcChannel(connection);
}
}
| hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.client;
import com.google.protobuf.ByteString;
import com.google.protobuf.ServiceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Abortable;
import org.apache.hadoop.hbase.ClusterStatus;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.catalog.CatalogTracker;
import org.apache.hadoop.hbase.catalog.MetaReader;
import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitor;
import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitorBase;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.exceptions.FailedLogCloseException;
import org.apache.hadoop.hbase.exceptions.HBaseSnapshotException;
import org.apache.hadoop.hbase.exceptions.MasterNotRunningException;
import org.apache.hadoop.hbase.exceptions.NotServingRegionException;
import org.apache.hadoop.hbase.exceptions.RegionException;
import org.apache.hadoop.hbase.exceptions.RestoreSnapshotException;
import org.apache.hadoop.hbase.exceptions.SnapshotCreationException;
import org.apache.hadoop.hbase.exceptions.TableExistsException;
import org.apache.hadoop.hbase.exceptions.TableNotEnabledException;
import org.apache.hadoop.hbase.exceptions.TableNotFoundException;
import org.apache.hadoop.hbase.exceptions.UnknownRegionException;
import org.apache.hadoop.hbase.exceptions.UnknownSnapshotException;
import org.apache.hadoop.hbase.exceptions.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
import org.apache.hadoop.hbase.ipc.MasterCoprocessorRpcChannel;
import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.protobuf.RequestConverter;
import org.apache.hadoop.hbase.protobuf.ResponseConverter;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionResponse;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CompactRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.FlushRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse.CompactionState;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterRequest;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterResponse;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.StopServerRequest;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.TableSchema;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.AddColumnRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.AssignRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.CreateTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.DeleteColumnRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.DeleteSnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.DeleteTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.DisableTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.EnableTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.IsRestoreSnapshotDoneRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.IsRestoreSnapshotDoneResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.IsSnapshotDoneRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.IsSnapshotDoneResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.ListSnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.ModifyColumnRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.ModifyTableRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.MoveRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.RestoreSnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.RestoreSnapshotResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.SetBalancerRunningRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.ShutdownRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.StopMasterRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.TakeSnapshotRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.TakeSnapshotResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.UnassignRegionRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetClusterStatusRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetSchemaAlterStatusRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetSchemaAlterStatusResponse;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsRequest;
import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsResponse;
import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
import org.apache.hadoop.hbase.util.Addressing;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.util.StringUtils;
import org.apache.zookeeper.KeeperException;
import java.io.Closeable;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
/**
* Provides an interface to manage HBase database table metadata + general
* administrative functions. Use HBaseAdmin to create, drop, list, enable and
* disable tables. Use it also to add and drop table column families.
*
* <p>See {@link HTable} to add, update, and delete data from an individual table.
* <p>Currently HBaseAdmin instances are not expected to be long-lived. For
* example, an HBaseAdmin instance will not ride over a Master restart.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class HBaseAdmin implements Abortable, Closeable {
private static final Log LOG = LogFactory.getLog(HBaseAdmin.class);
// We use the implementation class rather then the interface because we
// need the package protected functions to get the connection to master
private HConnection connection;
private volatile Configuration conf;
private final long pause;
private final int numRetries;
// Some operations can take a long time such as disable of big table.
// numRetries is for 'normal' stuff... Multiply by this factor when
// want to wait a long time.
private final int retryLongerMultiplier;
private boolean aborted;
/**
* Constructor.
* See {@link #HBaseAdmin(HConnection connection)}
*
* @param c Configuration object. Copied internally.
*/
public HBaseAdmin(Configuration c)
throws MasterNotRunningException, ZooKeeperConnectionException {
// Will not leak connections, as the new implementation of the constructor
// does not throw exceptions anymore.
this(HConnectionManager.getConnection(new Configuration(c)));
}
/**
* Constructor for externally managed HConnections.
* The connection to master will be created when required by admin functions.
*
* @param connection The HConnection instance to use
* @throws MasterNotRunningException, ZooKeeperConnectionException are not
* thrown anymore but kept into the interface for backward api compatibility
*/
public HBaseAdmin(HConnection connection)
throws MasterNotRunningException, ZooKeeperConnectionException {
this.conf = connection.getConfiguration();
this.connection = connection;
this.pause = this.conf.getLong("hbase.client.pause", 1000);
this.numRetries = this.conf.getInt("hbase.client.retries.number", 10);
this.retryLongerMultiplier = this.conf.getInt(
"hbase.client.retries.longer.multiplier", 10);
}
/**
* @return A new CatalogTracker instance; call {@link #cleanupCatalogTracker(CatalogTracker)}
* to cleanup the returned catalog tracker.
* @throws org.apache.hadoop.hbase.exceptions.ZooKeeperConnectionException
* @throws IOException
* @see #cleanupCatalogTracker(CatalogTracker)
*/
private synchronized CatalogTracker getCatalogTracker()
throws ZooKeeperConnectionException, IOException {
CatalogTracker ct = null;
try {
ct = new CatalogTracker(this.conf);
ct.start();
} catch (InterruptedException e) {
// Let it out as an IOE for now until we redo all so tolerate IEs
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e);
}
return ct;
}
private void cleanupCatalogTracker(final CatalogTracker ct) {
ct.stop();
}
@Override
public void abort(String why, Throwable e) {
// Currently does nothing but throw the passed message and exception
this.aborted = true;
throw new RuntimeException(why, e);
}
@Override
public boolean isAborted(){
return this.aborted;
}
/** @return HConnection used by this object. */
public HConnection getConnection() {
return connection;
}
/** @return - true if the master server is running. Throws an exception
* otherwise.
* @throws ZooKeeperConnectionException
* @throws MasterNotRunningException
*/
public boolean isMasterRunning()
throws MasterNotRunningException, ZooKeeperConnectionException {
return connection.isMasterRunning();
}
/**
* @param tableName Table to check.
* @return True if table exists already.
* @throws IOException
*/
public boolean tableExists(final String tableName)
throws IOException {
boolean b = false;
CatalogTracker ct = getCatalogTracker();
try {
b = MetaReader.tableExists(ct, tableName);
} finally {
cleanupCatalogTracker(ct);
}
return b;
}
/**
* @param tableName Table to check.
* @return True if table exists already.
* @throws IOException
*/
public boolean tableExists(final byte [] tableName)
throws IOException {
return tableExists(Bytes.toString(tableName));
}
/**
* List all the userspace tables. In other words, scan the META table.
*
* If we wanted this to be really fast, we could implement a special
* catalog table that just contains table names and their descriptors.
* Right now, it only exists as part of the META table's region info.
*
* @return - returns an array of HTableDescriptors
* @throws IOException if a remote or network exception occurs
*/
public HTableDescriptor[] listTables() throws IOException {
return this.connection.listTables();
}
/**
* List all the userspace tables matching the given pattern.
*
* @param pattern The compiled regular expression to match against
* @return - returns an array of HTableDescriptors
* @throws IOException if a remote or network exception occurs
* @see #listTables()
*/
public HTableDescriptor[] listTables(Pattern pattern) throws IOException {
List<HTableDescriptor> matched = new LinkedList<HTableDescriptor>();
HTableDescriptor[] tables = listTables();
for (HTableDescriptor table : tables) {
if (pattern.matcher(table.getNameAsString()).matches()) {
matched.add(table);
}
}
return matched.toArray(new HTableDescriptor[matched.size()]);
}
/**
* List all the userspace tables matching the given regular expression.
*
* @param regex The regular expression to match against
* @return - returns an array of HTableDescriptors
* @throws IOException if a remote or network exception occurs
* @see #listTables(java.util.regex.Pattern)
*/
public HTableDescriptor[] listTables(String regex) throws IOException {
return listTables(Pattern.compile(regex));
}
/**
* Method for getting the tableDescriptor
* @param tableName as a byte []
* @return the tableDescriptor
* @throws TableNotFoundException
* @throws IOException if a remote or network exception occurs
*/
public HTableDescriptor getTableDescriptor(final byte [] tableName)
throws TableNotFoundException, IOException {
return this.connection.getHTableDescriptor(tableName);
}
private long getPauseTime(int tries) {
int triesCount = tries;
if (triesCount >= HConstants.RETRY_BACKOFF.length) {
triesCount = HConstants.RETRY_BACKOFF.length - 1;
}
return this.pause * HConstants.RETRY_BACKOFF[triesCount];
}
/**
* Creates a new table.
* Synchronous operation.
*
* @param desc table descriptor for table
*
* @throws IllegalArgumentException if the table name is reserved
* @throws MasterNotRunningException if master is not running
* @throws TableExistsException if table already exists (If concurrent
* threads, the table may have been created between test-for-existence
* and attempt-at-creation).
* @throws IOException if a remote or network exception occurs
*/
public void createTable(HTableDescriptor desc)
throws IOException {
createTable(desc, null);
}
/**
* Creates a new table with the specified number of regions. The start key
* specified will become the end key of the first region of the table, and
* the end key specified will become the start key of the last region of the
* table (the first region has a null start key and the last region has a
* null end key).
*
* BigInteger math will be used to divide the key range specified into
* enough segments to make the required number of total regions.
*
* Synchronous operation.
*
* @param desc table descriptor for table
* @param startKey beginning of key range
* @param endKey end of key range
* @param numRegions the total number of regions to create
*
* @throws IllegalArgumentException if the table name is reserved
* @throws MasterNotRunningException if master is not running
* @throws org.apache.hadoop.hbase.exceptions.TableExistsException if table already exists (If concurrent
* threads, the table may have been created between test-for-existence
* and attempt-at-creation).
* @throws IOException
*/
public void createTable(HTableDescriptor desc, byte [] startKey,
byte [] endKey, int numRegions)
throws IOException {
HTableDescriptor.isLegalTableName(desc.getName());
if(numRegions < 3) {
throw new IllegalArgumentException("Must create at least three regions");
} else if(Bytes.compareTo(startKey, endKey) >= 0) {
throw new IllegalArgumentException("Start key must be smaller than end key");
}
byte [][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3);
if(splitKeys == null || splitKeys.length != numRegions - 1) {
throw new IllegalArgumentException("Unable to split key range into enough regions");
}
createTable(desc, splitKeys);
}
/**
* Creates a new table with an initial set of empty regions defined by the
* specified split keys. The total number of regions created will be the
* number of split keys plus one. Synchronous operation.
* Note : Avoid passing empty split key.
*
* @param desc table descriptor for table
* @param splitKeys array of split keys for the initial regions of the table
*
* @throws IllegalArgumentException if the table name is reserved, if the split keys
* are repeated and if the split key has empty byte array.
* @throws MasterNotRunningException if master is not running
* @throws org.apache.hadoop.hbase.exceptions.TableExistsException if table already exists (If concurrent
* threads, the table may have been created between test-for-existence
* and attempt-at-creation).
* @throws IOException
*/
public void createTable(final HTableDescriptor desc, byte [][] splitKeys)
throws IOException {
HTableDescriptor.isLegalTableName(desc.getName());
try {
createTableAsync(desc, splitKeys);
} catch (SocketTimeoutException ste) {
LOG.warn("Creating " + desc.getNameAsString() + " took too long", ste);
}
int numRegs = splitKeys == null ? 1 : splitKeys.length + 1;
int prevRegCount = 0;
boolean doneWithMetaScan = false;
for (int tries = 0; tries < this.numRetries * this.retryLongerMultiplier;
++tries) {
if (!doneWithMetaScan) {
// Wait for new table to come on-line
final AtomicInteger actualRegCount = new AtomicInteger(0);
MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
@Override
public boolean processRow(Result rowResult) throws IOException {
HRegionInfo info = HRegionInfo.getHRegionInfo(rowResult);
if (info == null) {
LOG.warn("No serialized HRegionInfo in " + rowResult);
return true;
}
if (!(Bytes.equals(info.getTableName(), desc.getName()))) {
return false;
}
ServerName serverName = HRegionInfo.getServerName(rowResult);
// Make sure that regions are assigned to server
if (!(info.isOffline() || info.isSplit()) && serverName != null
&& serverName.getHostAndPort() != null) {
actualRegCount.incrementAndGet();
}
return true;
}
};
MetaScanner.metaScan(conf, visitor, desc.getName());
if (actualRegCount.get() != numRegs) {
if (tries == this.numRetries * this.retryLongerMultiplier - 1) {
throw new RegionOfflineException("Only " + actualRegCount.get() +
" of " + numRegs + " regions are online; retries exhausted.");
}
try { // Sleep
Thread.sleep(getPauseTime(tries));
} catch (InterruptedException e) {
throw new InterruptedIOException("Interrupted when opening" +
" regions; " + actualRegCount.get() + " of " + numRegs +
" regions processed so far");
}
if (actualRegCount.get() > prevRegCount) { // Making progress
prevRegCount = actualRegCount.get();
tries = -1;
}
} else {
doneWithMetaScan = true;
tries = -1;
}
} else if (isTableEnabled(desc.getName())) {
return;
} else {
try { // Sleep
Thread.sleep(getPauseTime(tries));
} catch (InterruptedException e) {
throw new InterruptedIOException("Interrupted when waiting" +
" for table to be enabled; meta scan was done");
}
}
}
throw new TableNotEnabledException(
"Retries exhausted while still waiting for table: "
+ desc.getNameAsString() + " to be enabled");
}
/**
* Creates a new table but does not block and wait for it to come online.
* Asynchronous operation. To check if the table exists, use
* {@link #isTableAvailable} -- it is not safe to create an HTable
* instance to this table before it is available.
* Note : Avoid passing empty split key.
* @param desc table descriptor for table
*
* @throws IllegalArgumentException Bad table name, if the split keys
* are repeated and if the split key has empty byte array.
* @throws MasterNotRunningException if master is not running
* @throws org.apache.hadoop.hbase.exceptions.TableExistsException if table already exists (If concurrent
* threads, the table may have been created between test-for-existence
* and attempt-at-creation).
* @throws IOException
*/
public void createTableAsync(
final HTableDescriptor desc, final byte [][] splitKeys)
throws IOException {
HTableDescriptor.isLegalTableName(desc.getName());
if(splitKeys != null && splitKeys.length > 0) {
Arrays.sort(splitKeys, Bytes.BYTES_COMPARATOR);
// Verify there are no duplicate split keys
byte [] lastKey = null;
for(byte [] splitKey : splitKeys) {
if (Bytes.compareTo(splitKey, HConstants.EMPTY_BYTE_ARRAY) == 0) {
throw new IllegalArgumentException(
"Empty split key must not be passed in the split keys.");
}
if(lastKey != null && Bytes.equals(splitKey, lastKey)) {
throw new IllegalArgumentException("All split keys must be unique, " +
"found duplicate: " + Bytes.toStringBinary(splitKey) +
", " + Bytes.toStringBinary(lastKey));
}
lastKey = splitKey;
}
}
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
CreateTableRequest request = RequestConverter.buildCreateTableRequest(desc, splitKeys);
masterAdmin.createTable(null, request);
return null;
}
});
}
/**
* Deletes a table.
* Synchronous operation.
*
* @param tableName name of table to delete
* @throws IOException if a remote or network exception occurs
*/
public void deleteTable(final String tableName) throws IOException {
deleteTable(Bytes.toBytes(tableName));
}
/**
* Deletes a table.
* Synchronous operation.
*
* @param tableName name of table to delete
* @throws IOException if a remote or network exception occurs
*/
public void deleteTable(final byte [] tableName) throws IOException {
HTableDescriptor.isLegalTableName(tableName);
HRegionLocation firstMetaServer = getFirstMetaServerForTable(tableName);
boolean tableExists = true;
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
DeleteTableRequest req = RequestConverter.buildDeleteTableRequest(tableName);
masterAdmin.deleteTable(null,req);
return null;
}
});
// Wait until all regions deleted
ClientProtocol server =
connection.getClient(firstMetaServer.getServerName());
for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
try {
Scan scan = MetaReader.getScanForTableName(tableName);
scan.addColumn(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER);
ScanRequest request = RequestConverter.buildScanRequest(
firstMetaServer.getRegionInfo().getRegionName(), scan, 1, true);
Result[] values = null;
// Get a batch at a time.
try {
ScanResponse response = server.scan(null, request);
values = ResponseConverter.getResults(response);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
// let us wait until .META. table is updated and
// HMaster removes the table from its HTableDescriptors
if (values == null || values.length == 0) {
tableExists = false;
GetTableDescriptorsResponse htds;
MasterMonitorKeepAliveConnection master = connection.getKeepAliveMasterMonitor();
try {
GetTableDescriptorsRequest req =
RequestConverter.buildGetTableDescriptorsRequest(null);
htds = master.getTableDescriptors(null, req);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
} finally {
master.close();
}
for (TableSchema ts : htds.getTableSchemaList()) {
if (Bytes.equals(tableName, ts.getName().toByteArray())) {
tableExists = true;
break;
}
}
if (!tableExists) {
break;
}
}
} catch (IOException ex) {
if(tries == numRetries - 1) { // no more tries left
if (ex instanceof RemoteException) {
throw ((RemoteException) ex).unwrapRemoteException();
}else {
throw ex;
}
}
}
try {
Thread.sleep(getPauseTime(tries));
} catch (InterruptedException e) {
// continue
}
}
if (tableExists) {
throw new IOException("Retries exhausted, it took too long to wait"+
" for the table " + Bytes.toString(tableName) + " to be deleted.");
}
// Delete cached information to prevent clients from using old locations
this.connection.clearRegionCache(tableName);
LOG.info("Deleted " + Bytes.toString(tableName));
}
/**
* Deletes tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.lang.String)} and
* {@link #deleteTable(byte[])}
*
* @param regex The regular expression to match table names against
* @return Table descriptors for tables that couldn't be deleted
* @throws IOException
* @see #deleteTables(java.util.regex.Pattern)
* @see #deleteTable(java.lang.String)
*/
public HTableDescriptor[] deleteTables(String regex) throws IOException {
return deleteTables(Pattern.compile(regex));
}
/**
* Delete tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and
* {@link #deleteTable(byte[])}
*
* @param pattern The pattern to match table names against
* @return Table descriptors for tables that couldn't be deleted
* @throws IOException
*/
public HTableDescriptor[] deleteTables(Pattern pattern) throws IOException {
List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
for (HTableDescriptor table : listTables(pattern)) {
try {
deleteTable(table.getName());
} catch (IOException ex) {
LOG.info("Failed to delete table " + table.getNameAsString(), ex);
failed.add(table);
}
}
return failed.toArray(new HTableDescriptor[failed.size()]);
}
public void enableTable(final String tableName)
throws IOException {
enableTable(Bytes.toBytes(tableName));
}
/**
* Enable a table. May timeout. Use {@link #enableTableAsync(byte[])}
* and {@link #isTableEnabled(byte[])} instead.
* The table has to be in disabled state for it to be enabled.
* @param tableName name of the table
* @throws IOException if a remote or network exception occurs
* There could be couple types of IOException
* TableNotFoundException means the table doesn't exist.
* TableNotDisabledException means the table isn't in disabled state.
* @see #isTableEnabled(byte[])
* @see #disableTable(byte[])
* @see #enableTableAsync(byte[])
*/
public void enableTable(final byte [] tableName)
throws IOException {
enableTableAsync(tableName);
// Wait until all regions are enabled
waitUntilTableIsEnabled(tableName);
LOG.info("Enabled table " + Bytes.toString(tableName));
}
/**
* Wait for the table to be enabled and available
* If enabling the table exceeds the retry period, an exception is thrown.
* @param tableName name of the table
* @throws IOException if a remote or network exception occurs or
* table is not enabled after the retries period.
*/
private void waitUntilTableIsEnabled(final byte[] tableName) throws IOException {
boolean enabled = false;
long start = EnvironmentEdgeManager.currentTimeMillis();
for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
enabled = isTableEnabled(tableName) && isTableAvailable(tableName);
if (enabled) {
break;
}
long sleep = getPauseTime(tries);
if (LOG.isDebugEnabled()) {
LOG.debug("Sleeping= " + sleep + "ms, waiting for all regions to be " +
"enabled in " + Bytes.toString(tableName));
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// Do this conversion rather than let it out because do not want to
// change the method signature.
throw new IOException("Interrupted", e);
}
}
if (!enabled) {
long msec = EnvironmentEdgeManager.currentTimeMillis() - start;
throw new IOException("Table '" + Bytes.toString(tableName) +
"' not yet enabled, after " + msec + "ms.");
}
}
public void enableTableAsync(final String tableName)
throws IOException {
enableTableAsync(Bytes.toBytes(tableName));
}
/**
* Brings a table on-line (enables it). Method returns immediately though
* enable of table may take some time to complete, especially if the table
* is large (All regions are opened as part of enabling process). Check
* {@link #isTableEnabled(byte[])} to learn when table is fully online. If
* table is taking too long to online, check server logs.
* @param tableName
* @throws IOException
* @since 0.90.0
*/
public void enableTableAsync(final byte [] tableName)
throws IOException {
HTableDescriptor.isLegalTableName(tableName);
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
LOG.info("Started enable of " + Bytes.toString(tableName));
EnableTableRequest req = RequestConverter.buildEnableTableRequest(tableName);
masterAdmin.enableTable(null,req);
return null;
}
});
}
/**
* Enable tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.lang.String)} and
* {@link #enableTable(byte[])}
*
* @param regex The regular expression to match table names against
* @throws IOException
* @see #enableTables(java.util.regex.Pattern)
* @see #enableTable(java.lang.String)
*/
public HTableDescriptor[] enableTables(String regex) throws IOException {
return enableTables(Pattern.compile(regex));
}
/**
* Enable tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and
* {@link #enableTable(byte[])}
*
* @param pattern The pattern to match table names against
* @throws IOException
*/
public HTableDescriptor[] enableTables(Pattern pattern) throws IOException {
List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
for (HTableDescriptor table : listTables(pattern)) {
if (isTableDisabled(table.getName())) {
try {
enableTable(table.getName());
} catch (IOException ex) {
LOG.info("Failed to enable table " + table.getNameAsString(), ex);
failed.add(table);
}
}
}
return failed.toArray(new HTableDescriptor[failed.size()]);
}
public void disableTableAsync(final String tableName) throws IOException {
disableTableAsync(Bytes.toBytes(tableName));
}
/**
* Starts the disable of a table. If it is being served, the master
* will tell the servers to stop serving it. This method returns immediately.
* The disable of a table can take some time if the table is large (all
* regions are closed as part of table disable operation).
* Call {@link #isTableDisabled(byte[])} to check for when disable completes.
* If table is taking too long to online, check server logs.
* @param tableName name of table
* @throws IOException if a remote or network exception occurs
* @see #isTableDisabled(byte[])
* @see #isTableEnabled(byte[])
* @since 0.90.0
*/
public void disableTableAsync(final byte [] tableName) throws IOException {
HTableDescriptor.isLegalTableName(tableName);
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
LOG.info("Started disable of " + Bytes.toString(tableName));
DisableTableRequest req = RequestConverter.buildDisableTableRequest(tableName);
masterAdmin.disableTable(null,req);
return null;
}
});
}
public void disableTable(final String tableName)
throws IOException {
disableTable(Bytes.toBytes(tableName));
}
/**
* Disable table and wait on completion. May timeout eventually. Use
* {@link #disableTableAsync(byte[])} and {@link #isTableDisabled(String)}
* instead.
* The table has to be in enabled state for it to be disabled.
* @param tableName
* @throws IOException
* There could be couple types of IOException
* TableNotFoundException means the table doesn't exist.
* TableNotEnabledException means the table isn't in enabled state.
*/
public void disableTable(final byte [] tableName)
throws IOException {
disableTableAsync(tableName);
// Wait until table is disabled
boolean disabled = false;
for (int tries = 0; tries < (this.numRetries * this.retryLongerMultiplier); tries++) {
disabled = isTableDisabled(tableName);
if (disabled) {
break;
}
long sleep = getPauseTime(tries);
if (LOG.isDebugEnabled()) {
LOG.debug("Sleeping= " + sleep + "ms, waiting for all regions to be " +
"disabled in " + Bytes.toString(tableName));
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
// Do this conversion rather than let it out because do not want to
// change the method signature.
Thread.currentThread().interrupt();
throw new IOException("Interrupted", e);
}
}
if (!disabled) {
throw new RegionException("Retries exhausted, it took too long to wait"+
" for the table " + Bytes.toString(tableName) + " to be disabled.");
}
LOG.info("Disabled " + Bytes.toString(tableName));
}
/**
* Disable tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.lang.String)} and
* {@link #disableTable(byte[])}
*
* @param regex The regular expression to match table names against
* @return Table descriptors for tables that couldn't be disabled
* @throws IOException
* @see #disableTables(java.util.regex.Pattern)
* @see #disableTable(java.lang.String)
*/
public HTableDescriptor[] disableTables(String regex) throws IOException {
return disableTables(Pattern.compile(regex));
}
/**
* Disable tables matching the passed in pattern and wait on completion.
*
* Warning: Use this method carefully, there is no prompting and the effect is
* immediate. Consider using {@link #listTables(java.util.regex.Pattern) } and
* {@link #disableTable(byte[])}
*
* @param pattern The pattern to match table names against
* @return Table descriptors for tables that couldn't be disabled
* @throws IOException
*/
public HTableDescriptor[] disableTables(Pattern pattern) throws IOException {
List<HTableDescriptor> failed = new LinkedList<HTableDescriptor>();
for (HTableDescriptor table : listTables(pattern)) {
if (isTableEnabled(table.getName())) {
try {
disableTable(table.getName());
} catch (IOException ex) {
LOG.info("Failed to disable table " + table.getNameAsString(), ex);
failed.add(table);
}
}
}
return failed.toArray(new HTableDescriptor[failed.size()]);
}
/**
* @param tableName name of table to check
* @return true if table is on-line
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableEnabled(String tableName) throws IOException {
return isTableEnabled(Bytes.toBytes(tableName));
}
/**
* @param tableName name of table to check
* @return true if table is on-line
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableEnabled(byte[] tableName) throws IOException {
if (!HTableDescriptor.isMetaTable(tableName)) {
HTableDescriptor.isLegalTableName(tableName);
}
return connection.isTableEnabled(tableName);
}
/**
* @param tableName name of table to check
* @return true if table is off-line
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableDisabled(final String tableName) throws IOException {
return isTableDisabled(Bytes.toBytes(tableName));
}
/**
* @param tableName name of table to check
* @return true if table is off-line
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableDisabled(byte[] tableName) throws IOException {
if (!HTableDescriptor.isMetaTable(tableName)) {
HTableDescriptor.isLegalTableName(tableName);
}
return connection.isTableDisabled(tableName);
}
/**
* @param tableName name of table to check
* @return true if all regions of the table are available
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableAvailable(byte[] tableName) throws IOException {
return connection.isTableAvailable(tableName);
}
/**
* @param tableName name of table to check
* @return true if all regions of the table are available
* @throws IOException if a remote or network exception occurs
*/
public boolean isTableAvailable(String tableName) throws IOException {
return connection.isTableAvailable(Bytes.toBytes(tableName));
}
/**
* Use this api to check if the table has been created with the specified number of
* splitkeys which was used while creating the given table.
* Note : If this api is used after a table's region gets splitted, the api may return
* false.
* @param tableName
* name of table to check
* @param splitKeys
* keys to check if the table has been created with all split keys
* @throws IOException
* if a remote or network excpetion occurs
*/
public boolean isTableAvailable(String tableName, byte[][] splitKeys) throws IOException {
return connection.isTableAvailable(Bytes.toBytes(tableName), splitKeys);
}
/**
* Use this api to check if the table has been created with the specified number of
* splitkeys which was used while creating the given table.
* Note : If this api is used after a table's region gets splitted, the api may return
* false.
* @param tableName
* name of table to check
* @param splitKeys
* keys to check if the table has been created with all split keys
* @throws IOException
* if a remote or network excpetion occurs
*/
public boolean isTableAvailable(byte[] tableName, byte[][] splitKeys) throws IOException {
return connection.isTableAvailable(tableName, splitKeys);
}
/**
* Get the status of alter command - indicates how many regions have received
* the updated schema Asynchronous operation.
*
* @param tableName
* name of the table to get the status of
* @return Pair indicating the number of regions updated Pair.getFirst() is the
* regions that are yet to be updated Pair.getSecond() is the total number
* of regions of the table
* @throws IOException
* if a remote or network exception occurs
*/
public Pair<Integer, Integer> getAlterStatus(final byte[] tableName)
throws IOException {
HTableDescriptor.isLegalTableName(tableName);
return execute(new MasterMonitorCallable<Pair<Integer, Integer>>() {
@Override
public Pair<Integer, Integer> call() throws ServiceException {
GetSchemaAlterStatusRequest req = RequestConverter
.buildGetSchemaAlterStatusRequest(tableName);
GetSchemaAlterStatusResponse ret = masterMonitor.getSchemaAlterStatus(null, req);
Pair<Integer, Integer> pair = new Pair<Integer, Integer>(Integer.valueOf(ret
.getYetToUpdateRegions()), Integer.valueOf(ret.getTotalRegions()));
return pair;
}
});
}
/**
* Add a column to an existing table.
* Asynchronous operation.
*
* @param tableName name of the table to add column to
* @param column column descriptor of column to be added
* @throws IOException if a remote or network exception occurs
*/
public void addColumn(final String tableName, HColumnDescriptor column)
throws IOException {
addColumn(Bytes.toBytes(tableName), column);
}
/**
* Add a column to an existing table.
* Asynchronous operation.
*
* @param tableName name of the table to add column to
* @param column column descriptor of column to be added
* @throws IOException if a remote or network exception occurs
*/
public void addColumn(final byte [] tableName, final HColumnDescriptor column)
throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
AddColumnRequest req = RequestConverter.buildAddColumnRequest(tableName, column);
masterAdmin.addColumn(null,req);
return null;
}
});
}
/**
* Delete a column from a table.
* Asynchronous operation.
*
* @param tableName name of table
* @param columnName name of column to be deleted
* @throws IOException if a remote or network exception occurs
*/
public void deleteColumn(final String tableName, final String columnName)
throws IOException {
deleteColumn(Bytes.toBytes(tableName), Bytes.toBytes(columnName));
}
/**
* Delete a column from a table.
* Asynchronous operation.
*
* @param tableName name of table
* @param columnName name of column to be deleted
* @throws IOException if a remote or network exception occurs
*/
public void deleteColumn(final byte [] tableName, final byte [] columnName)
throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
DeleteColumnRequest req = RequestConverter.buildDeleteColumnRequest(tableName, columnName);
masterAdmin.deleteColumn(null,req);
return null;
}
});
}
/**
* Modify an existing column family on a table.
* Asynchronous operation.
*
* @param tableName name of table
* @param descriptor new column descriptor to use
* @throws IOException if a remote or network exception occurs
*/
public void modifyColumn(final String tableName, HColumnDescriptor descriptor)
throws IOException {
modifyColumn(Bytes.toBytes(tableName), descriptor);
}
/**
* Modify an existing column family on a table.
* Asynchronous operation.
*
* @param tableName name of table
* @param descriptor new column descriptor to use
* @throws IOException if a remote or network exception occurs
*/
public void modifyColumn(final byte [] tableName, final HColumnDescriptor descriptor)
throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
ModifyColumnRequest req = RequestConverter.buildModifyColumnRequest(tableName, descriptor);
masterAdmin.modifyColumn(null,req);
return null;
}
});
}
/**
* Close a region. For expert-admins. Runs close on the regionserver. The
* master will not be informed of the close.
* @param regionname region name to close
* @param serverName If supplied, we'll use this location rather than
* the one currently in <code>.META.</code>
* @throws IOException if a remote or network exception occurs
*/
public void closeRegion(final String regionname, final String serverName)
throws IOException {
closeRegion(Bytes.toBytesBinary(regionname), serverName);
}
/**
* Close a region. For expert-admins Runs close on the regionserver. The
* master will not be informed of the close.
* @param regionname region name to close
* @param serverName The servername of the regionserver. If passed null we
* will use servername found in the .META. table. A server name
* is made of host, port and startcode. Here is an example:
* <code> host187.example.com,60020,1289493121758</code>
* @throws IOException if a remote or network exception occurs
*/
public void closeRegion(final byte [] regionname, final String serverName)
throws IOException {
CatalogTracker ct = getCatalogTracker();
try {
if (serverName != null) {
Pair<HRegionInfo, ServerName> pair = MetaReader.getRegion(ct, regionname);
if (pair == null || pair.getFirst() == null) {
throw new UnknownRegionException(Bytes.toStringBinary(regionname));
} else {
closeRegion(new ServerName(serverName), pair.getFirst());
}
} else {
Pair<HRegionInfo, ServerName> pair = MetaReader.getRegion(ct, regionname);
if (pair == null) {
throw new UnknownRegionException(Bytes.toStringBinary(regionname));
} else if (pair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(regionname));
} else {
closeRegion(pair.getSecond(), pair.getFirst());
}
}
} finally {
cleanupCatalogTracker(ct);
}
}
/**
* For expert-admins. Runs close on the regionserver. Closes a region based on
* the encoded region name. The region server name is mandatory. If the
* servername is provided then based on the online regions in the specified
* regionserver the specified region will be closed. The master will not be
* informed of the close. Note that the regionname is the encoded regionname.
*
* @param encodedRegionName
* The encoded region name; i.e. the hash that makes up the region
* name suffix: e.g. if regionname is
* <code>TestTable,0094429456,1289497600452.527db22f95c8a9e0116f0cc13c680396.</code>
* , then the encoded region name is:
* <code>527db22f95c8a9e0116f0cc13c680396</code>.
* @param serverName
* The servername of the regionserver. A server name is made of host,
* port and startcode. This is mandatory. Here is an example:
* <code> host187.example.com,60020,1289493121758</code>
* @return true if the region was closed, false if not.
* @throws IOException
* if a remote or network exception occurs
*/
public boolean closeRegionWithEncodedRegionName(final String encodedRegionName,
final String serverName) throws IOException {
if (null == serverName || ("").equals(serverName.trim())) {
throw new IllegalArgumentException(
"The servername cannot be null or empty.");
}
ServerName sn = new ServerName(serverName);
AdminProtocol admin = this.connection.getAdmin(sn);
// Close the region without updating zk state.
CloseRegionRequest request =
RequestConverter.buildCloseRegionRequest(encodedRegionName, false);
try {
CloseRegionResponse response = admin.closeRegion(null, request);
boolean isRegionClosed = response.getClosed();
if (false == isRegionClosed) {
LOG.error("Not able to close the region " + encodedRegionName + ".");
}
return isRegionClosed;
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
/**
* Close a region. For expert-admins Runs close on the regionserver. The
* master will not be informed of the close.
* @param sn
* @param hri
* @throws IOException
*/
public void closeRegion(final ServerName sn, final HRegionInfo hri)
throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
// Close the region without updating zk state.
ProtobufUtil.closeRegion(admin, hri.getRegionName(), false);
}
/**
* Get all the online regions on a region server.
*/
public List<HRegionInfo> getOnlineRegions(
final ServerName sn) throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
return ProtobufUtil.getOnlineRegions(admin);
}
/**
* Flush a table or an individual region.
* Synchronous operation.
*
* @param tableNameOrRegionName table or region to flush
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void flush(final String tableNameOrRegionName)
throws IOException, InterruptedException {
flush(Bytes.toBytesBinary(tableNameOrRegionName));
}
/**
* Flush a table or an individual region.
* Synchronous operation.
*
* @param tableNameOrRegionName table or region to flush
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void flush(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
CatalogTracker ct = getCatalogTracker();
try {
Pair<HRegionInfo, ServerName> regionServerPair
= getRegion(tableNameOrRegionName, ct);
if (regionServerPair != null) {
if (regionServerPair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
} else {
flush(regionServerPair.getSecond(), regionServerPair.getFirst());
}
} else {
final String tableName = tableNameString(tableNameOrRegionName, ct);
List<Pair<HRegionInfo, ServerName>> pairs =
MetaReader.getTableRegionsAndLocations(ct,
tableName);
for (Pair<HRegionInfo, ServerName> pair: pairs) {
if (pair.getFirst().isOffline()) continue;
if (pair.getSecond() == null) continue;
try {
flush(pair.getSecond(), pair.getFirst());
} catch (NotServingRegionException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to flush " + pair.getFirst() + ": " +
StringUtils.stringifyException(e));
}
}
}
}
} finally {
cleanupCatalogTracker(ct);
}
}
private void flush(final ServerName sn, final HRegionInfo hri)
throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
FlushRegionRequest request =
RequestConverter.buildFlushRegionRequest(hri.getRegionName());
try {
admin.flushRegion(null, request);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
/**
* Compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void compact(final String tableNameOrRegionName)
throws IOException, InterruptedException {
compact(Bytes.toBytesBinary(tableNameOrRegionName));
}
/**
* Compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void compact(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
compact(tableNameOrRegionName, null, false);
}
/**
* Compact a column family within a table or region.
* Asynchronous operation.
*
* @param tableOrRegionName table or region to compact
* @param columnFamily column family within a table or region
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void compact(String tableOrRegionName, String columnFamily)
throws IOException, InterruptedException {
compact(Bytes.toBytesBinary(tableOrRegionName), Bytes.toBytes(columnFamily));
}
/**
* Compact a column family within a table or region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to compact
* @param columnFamily column family within a table or region
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void compact(final byte [] tableNameOrRegionName, final byte[] columnFamily)
throws IOException, InterruptedException {
compact(tableNameOrRegionName, columnFamily, false);
}
/**
* Major compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to major compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void majorCompact(final String tableNameOrRegionName)
throws IOException, InterruptedException {
majorCompact(Bytes.toBytesBinary(tableNameOrRegionName));
}
/**
* Major compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to major compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void majorCompact(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
compact(tableNameOrRegionName, null, true);
}
/**
* Major compact a column family within a table or region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to major compact
* @param columnFamily column family within a table or region
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void majorCompact(final String tableNameOrRegionName,
final String columnFamily) throws IOException, InterruptedException {
majorCompact(Bytes.toBytes(tableNameOrRegionName),
Bytes.toBytes(columnFamily));
}
/**
* Major compact a column family within a table or region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to major compact
* @param columnFamily column family within a table or region
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void majorCompact(final byte [] tableNameOrRegionName,
final byte[] columnFamily) throws IOException, InterruptedException {
compact(tableNameOrRegionName, columnFamily, true);
}
/**
* Compact a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to compact
* @param columnFamily column family within a table or region
* @param major True if we are to do a major compaction.
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
private void compact(final byte [] tableNameOrRegionName,
final byte[] columnFamily,final boolean major)
throws IOException, InterruptedException {
CatalogTracker ct = getCatalogTracker();
try {
Pair<HRegionInfo, ServerName> regionServerPair
= getRegion(tableNameOrRegionName, ct);
if (regionServerPair != null) {
if (regionServerPair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
} else {
compact(regionServerPair.getSecond(), regionServerPair.getFirst(), major, columnFamily);
}
} else {
final String tableName = tableNameString(tableNameOrRegionName, ct);
List<Pair<HRegionInfo, ServerName>> pairs =
MetaReader.getTableRegionsAndLocations(ct,
tableName);
for (Pair<HRegionInfo, ServerName> pair: pairs) {
if (pair.getFirst().isOffline()) continue;
if (pair.getSecond() == null) continue;
try {
compact(pair.getSecond(), pair.getFirst(), major, columnFamily);
} catch (NotServingRegionException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to" + (major ? " major" : "") + " compact " +
pair.getFirst() + ": " +
StringUtils.stringifyException(e));
}
}
}
}
} finally {
cleanupCatalogTracker(ct);
}
}
private void compact(final ServerName sn, final HRegionInfo hri,
final boolean major, final byte [] family)
throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
CompactRegionRequest request =
RequestConverter.buildCompactRegionRequest(hri.getRegionName(), major, family);
try {
admin.compactRegion(null, request);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
/**
* Move the region <code>r</code> to <code>dest</code>.
* @param encodedRegionName The encoded region name; i.e. the hash that makes
* up the region name suffix: e.g. if regionname is
* <code>TestTable,0094429456,1289497600452.527db22f95c8a9e0116f0cc13c680396.</code>,
* then the encoded region name is: <code>527db22f95c8a9e0116f0cc13c680396</code>.
* @param destServerName The servername of the destination regionserver. If
* passed the empty byte array we'll assign to a random server. A server name
* is made of host, port and startcode. Here is an example:
* <code> host187.example.com,60020,1289493121758</code>
* @throws UnknownRegionException Thrown if we can't find a region named
* <code>encodedRegionName</code>
* @throws ZooKeeperConnectionException
* @throws MasterNotRunningException
*/
public void move(final byte [] encodedRegionName, final byte [] destServerName)
throws UnknownRegionException, MasterNotRunningException, ZooKeeperConnectionException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
MoveRegionRequest request = RequestConverter.buildMoveRegionRequest(encodedRegionName, destServerName);
master.moveRegion(null,request);
} catch (ServiceException se) {
IOException ioe = ProtobufUtil.getRemoteException(se);
if (ioe instanceof UnknownRegionException) {
throw (UnknownRegionException)ioe;
}
LOG.error("Unexpected exception: " + se + " from calling HMaster.moveRegion");
} catch (DeserializationException de) {
LOG.error("Could not parse destination server name: " + de);
}
finally {
master.close();
}
}
/**
* @param regionName
* Region name to assign.
* @throws MasterNotRunningException
* @throws ZooKeeperConnectionException
* @throws IOException
*/
public void assign(final byte[] regionName) throws MasterNotRunningException,
ZooKeeperConnectionException, IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
AssignRegionRequest request = RequestConverter.buildAssignRegionRequest(regionName);
masterAdmin.assignRegion(null,request);
return null;
}
});
}
/**
* Unassign a region from current hosting regionserver. Region will then be
* assigned to a regionserver chosen at random. Region could be reassigned
* back to the same server. Use {@link #move(byte[], byte[])} if you want
* to control the region movement.
* @param regionName Region to unassign. Will clear any existing RegionPlan
* if one found.
* @param force If true, force unassign (Will remove region from
* regions-in-transition too if present. If results in double assignment
* use hbck -fix to resolve. To be used by experts).
* @throws MasterNotRunningException
* @throws ZooKeeperConnectionException
* @throws IOException
*/
public void unassign(final byte [] regionName, final boolean force)
throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
UnassignRegionRequest request =
RequestConverter.buildUnassignRegionRequest(regionName, force);
masterAdmin.unassignRegion(null,request);
return null;
}
});
}
/**
* Special method, only used by hbck.
*/
public void offline(final byte [] regionName)
throws IOException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
master.offlineRegion(null,RequestConverter.buildOfflineRegionRequest(regionName));
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
} finally {
master.close();
}
}
/**
* Turn the load balancer on or off.
* @param on If true, enable balancer. If false, disable balancer.
* @param synchronous If true, it waits until current balance() call, if outstanding, to return.
* @return Previous balancer value
*/
public boolean setBalancerRunning(final boolean on, final boolean synchronous)
throws MasterNotRunningException, ZooKeeperConnectionException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
SetBalancerRunningRequest req =
RequestConverter.buildSetBalancerRunningRequest(on, synchronous);
return master.setBalancerRunning(null, req).getPrevBalanceValue();
} catch (ServiceException se) {
IOException ioe = ProtobufUtil.getRemoteException(se);
if (ioe instanceof MasterNotRunningException) {
throw (MasterNotRunningException)ioe;
}
if (ioe instanceof ZooKeeperConnectionException) {
throw (ZooKeeperConnectionException)ioe;
}
// Throwing MasterNotRunningException even though not really valid in order to not
// break interface by adding additional exception type.
throw new MasterNotRunningException("Unexpected exception when calling balanceSwitch",se);
} finally {
master.close();
}
}
/**
* Invoke the balancer. Will run the balancer and if regions to move, it will
* go ahead and do the reassignments. Can NOT run for various reasons. Check
* logs.
* @return True if balancer ran, false otherwise.
*/
public boolean balancer()
throws MasterNotRunningException, ZooKeeperConnectionException, ServiceException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
return master.balance(null,RequestConverter.buildBalanceRequest()).getBalancerRan();
} finally {
master.close();
}
}
/**
* Enable/Disable the catalog janitor
* @param enable if true enables the catalog janitor
* @return the previous state
* @throws ServiceException
* @throws MasterNotRunningException
*/
public boolean enableCatalogJanitor(boolean enable)
throws ServiceException, MasterNotRunningException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
return master.enableCatalogJanitor(null,
RequestConverter.buildEnableCatalogJanitorRequest(enable)).getPrevValue();
} finally {
master.close();
}
}
/**
* Ask for a scan of the catalog table
* @return the number of entries cleaned
* @throws ServiceException
* @throws MasterNotRunningException
*/
public int runCatalogScan() throws ServiceException, MasterNotRunningException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
return master.runCatalogScan(null,
RequestConverter.buildCatalogScanRequest()).getScanResult();
} finally {
master.close();
}
}
/**
* Query on the catalog janitor state (Enabled/Disabled?)
* @throws ServiceException
* @throws org.apache.hadoop.hbase.exceptions.MasterNotRunningException
*/
public boolean isCatalogJanitorEnabled() throws ServiceException, MasterNotRunningException {
MasterAdminKeepAliveConnection master = connection.getKeepAliveMasterAdmin();
try {
return master.isCatalogJanitorEnabled(null,
RequestConverter.buildIsCatalogJanitorEnabledRequest()).getValue();
} finally {
master.close();
}
}
/**
* Split a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table or region to split
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void split(final String tableNameOrRegionName)
throws IOException, InterruptedException {
split(Bytes.toBytesBinary(tableNameOrRegionName));
}
/**
* Split a table or an individual region. Implicitly finds an optimal split
* point. Asynchronous operation.
*
* @param tableNameOrRegionName table to region to split
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
*/
public void split(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
split(tableNameOrRegionName, null);
}
public void split(final String tableNameOrRegionName,
final String splitPoint) throws IOException, InterruptedException {
split(Bytes.toBytesBinary(tableNameOrRegionName), Bytes.toBytesBinary(splitPoint));
}
/**
* Split a table or an individual region.
* Asynchronous operation.
*
* @param tableNameOrRegionName table to region to split
* @param splitPoint the explicit position to split on
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException interrupt exception occurred
*/
public void split(final byte [] tableNameOrRegionName,
final byte [] splitPoint) throws IOException, InterruptedException {
CatalogTracker ct = getCatalogTracker();
try {
Pair<HRegionInfo, ServerName> regionServerPair
= getRegion(tableNameOrRegionName, ct);
if (regionServerPair != null) {
if (regionServerPair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
} else {
split(regionServerPair.getSecond(), regionServerPair.getFirst(), splitPoint);
}
} else {
final String tableName = tableNameString(tableNameOrRegionName, ct);
List<Pair<HRegionInfo, ServerName>> pairs =
MetaReader.getTableRegionsAndLocations(ct,
tableName);
for (Pair<HRegionInfo, ServerName> pair: pairs) {
// May not be a server for a particular row
if (pair.getSecond() == null) continue;
HRegionInfo r = pair.getFirst();
// check for parents
if (r.isSplitParent()) continue;
// if a split point given, only split that particular region
if (splitPoint != null && !r.containsRow(splitPoint)) continue;
// call out to region server to do split now
split(pair.getSecond(), pair.getFirst(), splitPoint);
}
}
} finally {
cleanupCatalogTracker(ct);
}
}
private void split(final ServerName sn, final HRegionInfo hri,
byte[] splitPoint) throws IOException {
AdminProtocol admin =
this.connection.getAdmin(sn);
ProtobufUtil.split(admin, hri, splitPoint);
}
/**
* Modify an existing table, more IRB friendly version.
* Asynchronous operation. This means that it may be a while before your
* schema change is updated across all of the table.
*
* @param tableName name of table.
* @param htd modified description of the table
* @throws IOException if a remote or network exception occurs
*/
public void modifyTable(final byte [] tableName, final HTableDescriptor htd)
throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
ModifyTableRequest request = RequestConverter.buildModifyTableRequest(tableName, htd);
masterAdmin.modifyTable(null, request);
return null;
}
});
}
/**
* @param tableNameOrRegionName Name of a table or name of a region.
* @param ct A {@link CatalogTracker} instance (caller of this method usually has one).
* @return a pair of HRegionInfo and ServerName if <code>tableNameOrRegionName</code> is
* a verified region name (we call {@link MetaReader#getRegion( CatalogTracker, byte[])}
* else null.
* Throw an exception if <code>tableNameOrRegionName</code> is null.
* @throws IOException
*/
Pair<HRegionInfo, ServerName> getRegion(final byte[] tableNameOrRegionName,
final CatalogTracker ct) throws IOException {
if (tableNameOrRegionName == null) {
throw new IllegalArgumentException("Pass a table name or region name");
}
Pair<HRegionInfo, ServerName> pair = MetaReader.getRegion(ct, tableNameOrRegionName);
if (pair == null) {
final AtomicReference<Pair<HRegionInfo, ServerName>> result =
new AtomicReference<Pair<HRegionInfo, ServerName>>(null);
final String encodedName = Bytes.toString(tableNameOrRegionName);
MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
@Override
public boolean processRow(Result data) throws IOException {
HRegionInfo info = HRegionInfo.getHRegionInfo(data);
if (info == null) {
LOG.warn("No serialized HRegionInfo in " + data);
return true;
}
if (!encodedName.equals(info.getEncodedName())) return true;
ServerName sn = HRegionInfo.getServerName(data);
result.set(new Pair<HRegionInfo, ServerName>(info, sn));
return false; // found the region, stop
}
};
MetaScanner.metaScan(conf, visitor);
pair = result.get();
}
return pair;
}
/**
* Convert the table name byte array into a table name string and check if table
* exists or not.
* @param tableNameBytes Name of a table.
* @param ct A {@link CatalogTracker} instance (caller of this method usually has one).
* @return tableName in string form.
* @throws IOException if a remote or network exception occurs.
* @throws TableNotFoundException if table does not exist.
*/
private String tableNameString(final byte[] tableNameBytes, CatalogTracker ct)
throws IOException {
String tableNameString = Bytes.toString(tableNameBytes);
if (!MetaReader.tableExists(ct, tableNameString)) {
throw new TableNotFoundException(tableNameString);
}
return tableNameString;
}
/**
* Shuts down the HBase cluster
* @throws IOException if a remote or network exception occurs
*/
public synchronized void shutdown() throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
masterAdmin.shutdown(null,ShutdownRequest.newBuilder().build());
return null;
}
});
}
/**
* Shuts down the current HBase master only.
* Does not shutdown the cluster.
* @see #shutdown()
* @throws IOException if a remote or network exception occurs
*/
public synchronized void stopMaster() throws IOException {
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
masterAdmin.stopMaster(null,StopMasterRequest.newBuilder().build());
return null;
}
});
}
/**
* Stop the designated regionserver
* @param hostnamePort Hostname and port delimited by a <code>:</code> as in
* <code>example.org:1234</code>
* @throws IOException if a remote or network exception occurs
*/
public synchronized void stopRegionServer(final String hostnamePort)
throws IOException {
String hostname = Addressing.parseHostname(hostnamePort);
int port = Addressing.parsePort(hostnamePort);
AdminProtocol admin =
this.connection.getAdmin(new ServerName(hostname, port, 0));
StopServerRequest request = RequestConverter.buildStopServerRequest(
"Called by admin client " + this.connection.toString());
try {
admin.stopServer(null, request);
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
/**
* @return cluster status
* @throws IOException if a remote or network exception occurs
*/
public ClusterStatus getClusterStatus() throws IOException {
return execute(new MasterMonitorCallable<ClusterStatus>() {
@Override
public ClusterStatus call() throws ServiceException {
GetClusterStatusRequest req = RequestConverter.buildGetClusterStatusRequest();
return ClusterStatus.convert(masterMonitor.getClusterStatus(null,req).getClusterStatus());
}
});
}
private HRegionLocation getFirstMetaServerForTable(final byte [] tableName)
throws IOException {
return connection.locateRegion(HConstants.META_TABLE_NAME,
HRegionInfo.createRegionName(tableName, null, HConstants.NINES, false));
}
/**
* @return Configuration used by the instance.
*/
public Configuration getConfiguration() {
return this.conf;
}
/**
* Check to see if HBase is running. Throw an exception if not.
* We consider that HBase is running if ZooKeeper and Master are running.
*
* @param conf system configuration
* @throws MasterNotRunningException if the master is not running
* @throws ZooKeeperConnectionException if unable to connect to zookeeper
*/
public static void checkHBaseAvailable(Configuration conf)
throws MasterNotRunningException, ZooKeeperConnectionException, ServiceException {
Configuration copyOfConf = HBaseConfiguration.create(conf);
// We set it to make it fail as soon as possible if HBase is not available
copyOfConf.setInt("hbase.client.retries.number", 1);
copyOfConf.setInt("zookeeper.recovery.retry", 0);
HConnectionManager.HConnectionImplementation connection
= (HConnectionManager.HConnectionImplementation)
HConnectionManager.getConnection(copyOfConf);
try {
// Check ZK first.
// If the connection exists, we may have a connection to ZK that does
// not work anymore
ZooKeeperKeepAliveConnection zkw = null;
try {
zkw = connection.getKeepAliveZooKeeperWatcher();
zkw.getRecoverableZooKeeper().getZooKeeper().exists(
zkw.baseZNode, false);
} catch (IOException e) {
throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
} catch (KeeperException e) {
throw new ZooKeeperConnectionException("Can't connect to ZooKeeper", e);
} finally {
if (zkw != null) {
zkw.close();
}
}
// Check Master
connection.isMasterRunning();
} finally {
connection.close();
}
}
/**
* get the regions of a given table.
*
* @param tableName the name of the table
* @return Ordered list of {@link HRegionInfo}.
* @throws IOException
*/
public List<HRegionInfo> getTableRegions(final byte[] tableName)
throws IOException {
CatalogTracker ct = getCatalogTracker();
List<HRegionInfo> Regions = null;
try {
Regions = MetaReader.getTableRegions(ct, tableName, true);
} finally {
cleanupCatalogTracker(ct);
}
return Regions;
}
@Override
public void close() throws IOException {
if (this.connection != null) {
this.connection.close();
}
}
/**
* Get tableDescriptors
* @param tableNames List of table names
* @return HTD[] the tableDescriptor
* @throws IOException if a remote or network exception occurs
*/
public HTableDescriptor[] getTableDescriptors(List<String> tableNames)
throws IOException {
return this.connection.getHTableDescriptors(tableNames);
}
/**
* Roll the log writer. That is, start writing log messages to a new file.
*
* @param serverName
* The servername of the regionserver. A server name is made of host,
* port and startcode. This is mandatory. Here is an example:
* <code> host187.example.com,60020,1289493121758</code>
* @return If lots of logs, flush the returned regions so next time through
* we can clean logs. Returns null if nothing to flush. Names are actual
* region names as returned by {@link HRegionInfo#getEncodedName()}
* @throws IOException if a remote or network exception occurs
* @throws FailedLogCloseException
*/
public synchronized byte[][] rollHLogWriter(String serverName)
throws IOException, FailedLogCloseException {
ServerName sn = new ServerName(serverName);
AdminProtocol admin = this.connection.getAdmin(sn);
RollWALWriterRequest request = RequestConverter.buildRollWALWriterRequest();
try {
RollWALWriterResponse response = admin.rollWALWriter(null, request);
int regionCount = response.getRegionToFlushCount();
byte[][] regionsToFlush = new byte[regionCount][];
for (int i = 0; i < regionCount; i++) {
ByteString region = response.getRegionToFlush(i);
regionsToFlush[i] = region.toByteArray();
}
return regionsToFlush;
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
}
}
public String[] getMasterCoprocessors() {
try {
return getClusterStatus().getMasterCoprocessors();
} catch (IOException e) {
LOG.error("Could not getClusterStatus()",e);
return null;
}
}
/**
* Get the current compaction state of a table or region.
* It could be in a major compaction, a minor compaction, both, or none.
*
* @param tableNameOrRegionName table or region to major compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
* @return the current compaction state
*/
public CompactionState getCompactionState(final String tableNameOrRegionName)
throws IOException, InterruptedException {
return getCompactionState(Bytes.toBytes(tableNameOrRegionName));
}
/**
* Get the current compaction state of a table or region.
* It could be in a major compaction, a minor compaction, both, or none.
*
* @param tableNameOrRegionName table or region to major compact
* @throws IOException if a remote or network exception occurs
* @throws InterruptedException
* @return the current compaction state
*/
public CompactionState getCompactionState(final byte [] tableNameOrRegionName)
throws IOException, InterruptedException {
CompactionState state = CompactionState.NONE;
CatalogTracker ct = getCatalogTracker();
try {
Pair<HRegionInfo, ServerName> regionServerPair
= getRegion(tableNameOrRegionName, ct);
if (regionServerPair != null) {
if (regionServerPair.getSecond() == null) {
throw new NoServerForRegionException(Bytes.toStringBinary(tableNameOrRegionName));
} else {
ServerName sn = regionServerPair.getSecond();
AdminProtocol admin =
this.connection.getAdmin(sn);
GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
regionServerPair.getFirst().getRegionName(), true);
GetRegionInfoResponse response = admin.getRegionInfo(null, request);
return response.getCompactionState();
}
} else {
final String tableName = tableNameString(tableNameOrRegionName, ct);
List<Pair<HRegionInfo, ServerName>> pairs =
MetaReader.getTableRegionsAndLocations(ct, tableName);
for (Pair<HRegionInfo, ServerName> pair: pairs) {
if (pair.getFirst().isOffline()) continue;
if (pair.getSecond() == null) continue;
try {
ServerName sn = pair.getSecond();
AdminProtocol admin =
this.connection.getAdmin(sn);
GetRegionInfoRequest request = RequestConverter.buildGetRegionInfoRequest(
pair.getFirst().getRegionName(), true);
GetRegionInfoResponse response = admin.getRegionInfo(null, request);
switch (response.getCompactionState()) {
case MAJOR_AND_MINOR:
return CompactionState.MAJOR_AND_MINOR;
case MAJOR:
if (state == CompactionState.MINOR) {
return CompactionState.MAJOR_AND_MINOR;
}
state = CompactionState.MAJOR;
break;
case MINOR:
if (state == CompactionState.MAJOR) {
return CompactionState.MAJOR_AND_MINOR;
}
state = CompactionState.MINOR;
break;
case NONE:
default: // nothing, continue
}
} catch (NotServingRegionException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to get compaction state of " +
pair.getFirst() + ": " +
StringUtils.stringifyException(e));
}
}
}
}
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
} finally {
cleanupCatalogTracker(ct);
}
return state;
}
/**
* Take a snapshot for the given table. If the table is enabled, a FLUSH-type snapshot will be
* taken. If the table is disabled, an offline snapshot is taken.
* <p>
* Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
* snapshot with the same name (even a different type or with different parameters) will fail with
* a {@link SnapshotCreationException} indicating the duplicate naming.
* <p>
* Snapshot names follow the same naming constraints as tables in HBase. See
* {@link HTableDescriptor#isLegalTableName(byte[])}.
* @param snapshotName name of the snapshot to be created
* @param tableName name of the table for which snapshot is created
* @throws IOException if a remote or network exception occurs
* @throws SnapshotCreationException if snapshot creation failed
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public void snapshot(final String snapshotName, final String tableName) throws IOException,
SnapshotCreationException, IllegalArgumentException {
snapshot(snapshotName, tableName, SnapshotDescription.Type.FLUSH);
}
/**
* Create a timestamp consistent snapshot for the given table.
* <p>
* Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
* snapshot with the same name (even a different type or with different parameters) will fail with
* a {@link SnapshotCreationException} indicating the duplicate naming.
* <p>
* Snapshot names follow the same naming constraints as tables in HBase. See
* {@link HTableDescriptor#isLegalTableName(byte[])}.
* @param snapshotName name of the snapshot to be created
* @param tableName name of the table for which snapshot is created
* @throws IOException if a remote or network exception occurs
* @throws SnapshotCreationException if snapshot creation failed
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public void snapshot(final byte[] snapshotName, final byte[] tableName) throws IOException,
SnapshotCreationException, IllegalArgumentException {
snapshot(Bytes.toString(snapshotName), Bytes.toString(tableName));
}
/**
* Create typed snapshot of the table.
* <p>
* Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
* snapshot with the same name (even a different type or with different parameters) will fail with
* a {@link SnapshotCreationException} indicating the duplicate naming.
* <p>
* Snapshot names follow the same naming constraints as tables in HBase. See
* {@link HTableDescriptor#isLegalTableName(byte[])}.
* <p>
* @param snapshotName name to give the snapshot on the filesystem. Must be unique from all other
* snapshots stored on the cluster
* @param tableName name of the table to snapshot
* @param type type of snapshot to take
* @throws IOException we fail to reach the master
* @throws SnapshotCreationException if snapshot creation failed
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public void snapshot(final String snapshotName, final String tableName,
SnapshotDescription.Type type) throws IOException, SnapshotCreationException,
IllegalArgumentException {
SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
builder.setTable(tableName);
builder.setName(snapshotName);
builder.setType(type);
snapshot(builder.build());
}
/**
* Take a snapshot and wait for the server to complete that snapshot (blocking).
* <p>
* Only a single snapshot should be taken at a time for an instance of HBase, or results may be
* undefined (you can tell multiple HBase clusters to snapshot at the same time, but only one at a
* time for a single cluster).
* <p>
* Snapshots are considered unique based on <b>the name of the snapshot</b>. Attempts to take a
* snapshot with the same name (even a different type or with different parameters) will fail with
* a {@link SnapshotCreationException} indicating the duplicate naming.
* <p>
* Snapshot names follow the same naming constraints as tables in HBase. See
* {@link HTableDescriptor#isLegalTableName(byte[])}.
* <p>
* You should probably use {@link #snapshot(String, String)} or {@link #snapshot(byte[], byte[])}
* unless you are sure about the type of snapshot that you want to take.
* @param snapshot snapshot to take
* @throws IOException or we lose contact with the master.
* @throws SnapshotCreationException if snapshot failed to be taken
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public void snapshot(SnapshotDescription snapshot) throws IOException, SnapshotCreationException,
IllegalArgumentException {
// actually take the snapshot
TakeSnapshotResponse response = takeSnapshotAsync(snapshot);
final IsSnapshotDoneRequest request = IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot)
.build();
IsSnapshotDoneResponse done = null;
long start = EnvironmentEdgeManager.currentTimeMillis();
long max = response.getExpectedTimeout();
long maxPauseTime = max / this.numRetries;
int tries = 0;
LOG.debug("Waiting a max of " + max + " ms for snapshot '" +
ClientSnapshotDescriptionUtils.toString(snapshot) + "'' to complete. (max " +
maxPauseTime + " ms per retry)");
while (tries == 0
|| ((EnvironmentEdgeManager.currentTimeMillis() - start) < max && !done.getDone())) {
try {
// sleep a backoff <= pauseTime amount
long sleep = getPauseTime(tries++);
sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
LOG.debug("(#" + tries + ") Sleeping: " + sleep +
"ms while waiting for snapshot completion.");
Thread.sleep(sleep);
} catch (InterruptedException e) {
LOG.debug("Interrupted while waiting for snapshot " + snapshot + " to complete");
Thread.currentThread().interrupt();
}
LOG.debug("Getting current status of snapshot from master...");
done = execute(new MasterAdminCallable<IsSnapshotDoneResponse>() {
@Override
public IsSnapshotDoneResponse call() throws ServiceException {
return masterAdmin.isSnapshotDone(null, request);
}
});
};
if (!done.getDone()) {
throw new SnapshotCreationException("Snapshot '" + snapshot.getName()
+ "' wasn't completed in expectedTime:" + max + " ms", snapshot);
}
}
/**
* Take a snapshot without waiting for the server to complete that snapshot (asynchronous)
* <p>
* Only a single snapshot should be taken at a time, or results may be undefined.
* @param snapshot snapshot to take
* @return response from the server indicating the max time to wait for the snapshot
* @throws IOException if the snapshot did not succeed or we lose contact with the master.
* @throws SnapshotCreationException if snapshot creation failed
* @throws IllegalArgumentException if the snapshot request is formatted incorrectly
*/
public TakeSnapshotResponse takeSnapshotAsync(SnapshotDescription snapshot) throws IOException,
SnapshotCreationException {
ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
final TakeSnapshotRequest request = TakeSnapshotRequest.newBuilder().setSnapshot(snapshot)
.build();
// run the snapshot on the master
return execute(new MasterAdminCallable<TakeSnapshotResponse>() {
@Override
public TakeSnapshotResponse call() throws ServiceException {
return masterAdmin.snapshot(null, request);
}
});
}
/**
* Check the current state of the passed snapshot.
* <p>
* There are three possible states:
* <ol>
* <li>running - returns <tt>false</tt></li>
* <li>finished - returns <tt>true</tt></li>
* <li>finished with error - throws the exception that caused the snapshot to fail</li>
* </ol>
* <p>
* The cluster only knows about the most recent snapshot. Therefore, if another snapshot has been
* run/started since the snapshot your are checking, you will recieve an
* {@link UnknownSnapshotException}.
* @param snapshot description of the snapshot to check
* @return <tt>true</tt> if the snapshot is completed, <tt>false</tt> if the snapshot is still
* running
* @throws IOException if we have a network issue
* @throws HBaseSnapshotException if the snapshot failed
* @throws UnknownSnapshotException if the requested snapshot is unknown
*/
public boolean isSnapshotFinished(final SnapshotDescription snapshot)
throws IOException, HBaseSnapshotException, UnknownSnapshotException {
return execute(new MasterAdminCallable<IsSnapshotDoneResponse>() {
@Override
public IsSnapshotDoneResponse call() throws ServiceException {
return masterAdmin.isSnapshotDone(null,
IsSnapshotDoneRequest.newBuilder().setSnapshot(snapshot).build());
}
}).getDone();
}
/**
* Restore the specified snapshot on the original table. (The table must be disabled)
* Before restoring the table, a new snapshot with the current table state is created.
* In case of failure, the table will be rolled back to its original state.
*
* @param snapshotName name of the snapshot to restore
* @throws IOException if a remote or network exception occurs
* @throws RestoreSnapshotException if snapshot failed to be restored
* @throws IllegalArgumentException if the restore request is formatted incorrectly
*/
public void restoreSnapshot(final byte[] snapshotName)
throws IOException, RestoreSnapshotException {
restoreSnapshot(Bytes.toString(snapshotName));
}
/**
* Restore the specified snapshot on the original table. (The table must be disabled)
* Before restoring the table, a new snapshot with the current table state is created.
* In case of failure, the table will be rolled back to the its original state.
*
* @param snapshotName name of the snapshot to restore
* @throws IOException if a remote or network exception occurs
* @throws RestoreSnapshotException if snapshot failed to be restored
* @throws IllegalArgumentException if the restore request is formatted incorrectly
*/
public void restoreSnapshot(final String snapshotName)
throws IOException, RestoreSnapshotException {
String rollbackSnapshot = snapshotName + "-" + EnvironmentEdgeManager.currentTimeMillis();
String tableName = null;
for (SnapshotDescription snapshotInfo: listSnapshots()) {
if (snapshotInfo.getName().equals(snapshotName)) {
tableName = snapshotInfo.getTable();
break;
}
}
if (tableName == null) {
throw new RestoreSnapshotException(
"Unable to find the table name for snapshot=" + snapshotName);
}
// Take a snapshot of the current state
snapshot(rollbackSnapshot, tableName);
// Restore snapshot
try {
internalRestoreSnapshot(snapshotName, tableName);
} catch (IOException e) {
// Try to rollback
try {
String msg = "Restore snapshot=" + snapshotName +
" failed. Rollback to snapshot=" + rollbackSnapshot + " succeeded.";
LOG.error(msg, e);
internalRestoreSnapshot(rollbackSnapshot, tableName);
throw new RestoreSnapshotException(msg, e);
} catch (IOException ex) {
String msg = "Failed to restore and rollback to snapshot=" + rollbackSnapshot;
LOG.error(msg, ex);
throw new RestoreSnapshotException(msg, ex);
}
}
}
/**
* Create a new table by cloning the snapshot content.
*
* @param snapshotName name of the snapshot to be cloned
* @param tableName name of the table where the snapshot will be restored
* @throws IOException if a remote or network exception occurs
* @throws TableExistsException if table to be created already exists
* @throws RestoreSnapshotException if snapshot failed to be cloned
* @throws IllegalArgumentException if the specified table has not a valid name
*/
public void cloneSnapshot(final byte[] snapshotName, final byte[] tableName)
throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
cloneSnapshot(Bytes.toString(snapshotName), Bytes.toString(tableName));
}
/**
* Create a new table by cloning the snapshot content.
*
* @param snapshotName name of the snapshot to be cloned
* @param tableName name of the table where the snapshot will be restored
* @throws IOException if a remote or network exception occurs
* @throws TableExistsException if table to be created already exists
* @throws RestoreSnapshotException if snapshot failed to be cloned
* @throws IllegalArgumentException if the specified table has not a valid name
*/
public void cloneSnapshot(final String snapshotName, final String tableName)
throws IOException, TableExistsException, RestoreSnapshotException, InterruptedException {
if (tableExists(tableName)) {
throw new TableExistsException("Table '" + tableName + " already exists");
}
internalRestoreSnapshot(snapshotName, tableName);
waitUntilTableIsEnabled(Bytes.toBytes(tableName));
}
/**
* Execute Restore/Clone snapshot and wait for the server to complete (blocking).
* To check if the cloned table exists, use {@link #isTableAvailable} -- it is not safe to
* create an HTable instance to this table before it is available.
* @param snapshot snapshot to restore
* @param tableName table name to restore the snapshot on
* @throws IOException if a remote or network exception occurs
* @throws RestoreSnapshotException if snapshot failed to be restored
* @throws IllegalArgumentException if the restore request is formatted incorrectly
*/
private void internalRestoreSnapshot(final String snapshotName, final String tableName)
throws IOException, RestoreSnapshotException {
SnapshotDescription snapshot = SnapshotDescription.newBuilder()
.setName(snapshotName).setTable(tableName).build();
// actually restore the snapshot
internalRestoreSnapshotAsync(snapshot);
final IsRestoreSnapshotDoneRequest request = IsRestoreSnapshotDoneRequest.newBuilder()
.setSnapshot(snapshot).build();
IsRestoreSnapshotDoneResponse done = IsRestoreSnapshotDoneResponse.newBuilder().buildPartial();
final long maxPauseTime = 5000;
int tries = 0;
while (!done.getDone()) {
try {
// sleep a backoff <= pauseTime amount
long sleep = getPauseTime(tries++);
sleep = sleep > maxPauseTime ? maxPauseTime : sleep;
LOG.debug(tries + ") Sleeping: " + sleep + " ms while we wait for snapshot restore to complete.");
Thread.sleep(sleep);
} catch (InterruptedException e) {
LOG.debug("Interrupted while waiting for snapshot " + snapshot + " restore to complete");
Thread.currentThread().interrupt();
}
LOG.debug("Getting current status of snapshot restore from master...");
done = execute(new MasterAdminCallable<IsRestoreSnapshotDoneResponse>() {
@Override
public IsRestoreSnapshotDoneResponse call() throws ServiceException {
return masterAdmin.isRestoreSnapshotDone(null, request);
}
});
}
if (!done.getDone()) {
throw new RestoreSnapshotException("Snapshot '" + snapshot.getName() + "' wasn't restored.");
}
}
/**
* Execute Restore/Clone snapshot and wait for the server to complete (asynchronous)
* <p>
* Only a single snapshot should be restored at a time, or results may be undefined.
* @param snapshot snapshot to restore
* @return response from the server indicating the max time to wait for the snapshot
* @throws IOException if a remote or network exception occurs
* @throws RestoreSnapshotException if snapshot failed to be restored
* @throws IllegalArgumentException if the restore request is formatted incorrectly
*/
private RestoreSnapshotResponse internalRestoreSnapshotAsync(final SnapshotDescription snapshot)
throws IOException, RestoreSnapshotException {
ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
final RestoreSnapshotRequest request = RestoreSnapshotRequest.newBuilder().setSnapshot(snapshot)
.build();
// run the snapshot restore on the master
return execute(new MasterAdminCallable<RestoreSnapshotResponse>() {
@Override
public RestoreSnapshotResponse call() throws ServiceException {
return masterAdmin.restoreSnapshot(null, request);
}
});
}
/**
* List completed snapshots.
* @return a list of snapshot descriptors for completed snapshots
* @throws IOException if a network error occurs
*/
public List<SnapshotDescription> listSnapshots() throws IOException {
return execute(new MasterAdminCallable<List<SnapshotDescription>>() {
@Override
public List<SnapshotDescription> call() throws ServiceException {
return masterAdmin.getCompletedSnapshots(null, ListSnapshotRequest.newBuilder().build())
.getSnapshotsList();
}
});
}
/**
* Delete an existing snapshot.
* @param snapshotName name of the snapshot
* @throws IOException if a remote or network exception occurs
*/
public void deleteSnapshot(final byte[] snapshotName) throws IOException {
deleteSnapshot(Bytes.toString(snapshotName));
}
/**
* Delete an existing snapshot.
* @param snapshotName name of the snapshot
* @throws IOException if a remote or network exception occurs
*/
public void deleteSnapshot(final String snapshotName) throws IOException {
// make sure the snapshot is possibly valid
HTableDescriptor.isLegalTableName(Bytes.toBytes(snapshotName));
// do the delete
execute(new MasterAdminCallable<Void>() {
@Override
public Void call() throws ServiceException {
masterAdmin.deleteSnapshot(
null,
DeleteSnapshotRequest.newBuilder()
.setSnapshot(SnapshotDescription.newBuilder().setName(snapshotName).build()).build());
return null;
}
});
}
/**
* @see {@link #execute(MasterAdminCallable<V>)}
*/
private abstract static class MasterAdminCallable<V> implements Callable<V>{
protected MasterAdminKeepAliveConnection masterAdmin;
}
/**
* @see {@link #execute(MasterMonitorCallable<V>)}
*/
private abstract static class MasterMonitorCallable<V> implements Callable<V> {
protected MasterMonitorKeepAliveConnection masterMonitor;
}
/**
* This method allows to execute a function requiring a connection to
* master without having to manage the connection creation/close.
* Create a {@link MasterAdminCallable} to use it.
*/
private <V> V execute(MasterAdminCallable<V> function) throws IOException {
function.masterAdmin = connection.getKeepAliveMasterAdmin();
try {
return executeCallable(function);
} finally {
function.masterAdmin.close();
}
}
/**
* This method allows to execute a function requiring a connection to
* master without having to manage the connection creation/close.
* Create a {@link MasterAdminCallable} to use it.
*/
private <V> V execute(MasterMonitorCallable<V> function) throws IOException {
function.masterMonitor = connection.getKeepAliveMasterMonitor();
try {
return executeCallable(function);
} finally {
function.masterMonitor.close();
}
}
/**
* Helper function called by other execute functions.
*/
private <V> V executeCallable(Callable<V> function) throws IOException {
try {
return function.call();
} catch (RemoteException re) {
throw re.unwrapRemoteException();
} catch (IOException e) {
throw e;
} catch (ServiceException se) {
throw ProtobufUtil.getRemoteException(se);
} catch (Exception e) {
// This should not happen...
throw new IOException("Unexpected exception when calling master", e);
}
}
/**
* Creates and returns a {@link com.google.protobuf.RpcChannel} instance
* connected to the active master.
*
* <p>
* The obtained {@link com.google.protobuf.RpcChannel} instance can be used to access a published
* coprocessor {@link com.google.protobuf.Service} using standard protobuf service invocations:
* </p>
*
* <div style="background-color: #cccccc; padding: 2px">
* <blockquote><pre>
* CoprocessorRpcChannel channel = myAdmin.coprocessorService();
* MyService.BlockingInterface service = MyService.newBlockingStub(channel);
* MyCallRequest request = MyCallRequest.newBuilder()
* ...
* .build();
* MyCallResponse response = service.myCall(null, request);
* </pre></blockquote></div>
*
* @return A MasterCoprocessorRpcChannel instance
*/
public CoprocessorRpcChannel coprocessorService() {
return new MasterCoprocessorRpcChannel(connection);
}
}
| HBASE-8044 Revert, fixed by HBASE-6643
git-svn-id: 949c06ec81f1cb709fd2be51dd530a930344d7b3@1456604 13f79535-47bb-0310-9956-ffa450edef68
| hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java | HBASE-8044 Revert, fixed by HBASE-6643 |
|
Java | apache-2.0 | fdd4998551e0f0094f4f3b6273015a9cf77b06e5 | 0 | slipstream/SlipStreamServer,slipstream/SlipStreamServer,slipstream/SlipStreamServer,slipstream/SlipStreamServer | package com.sixsq.slipstream.user;
/*
* +=================================================================+
* SlipStream Server (WAR)
* =====
* Copyright (C) 2013 SixSq Sarl (sixsq.com)
* =====
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -=================================================================-
*/
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.restlet.data.Form;
import com.sixsq.slipstream.exceptions.BadlyFormedElementException;
import com.sixsq.slipstream.exceptions.NotFoundException;
import com.sixsq.slipstream.exceptions.SlipStreamClientException;
import com.sixsq.slipstream.exceptions.ValidationException;
import com.sixsq.slipstream.persistence.Parameter;
import com.sixsq.slipstream.persistence.ParameterType;
import com.sixsq.slipstream.persistence.Parameterized;
import com.sixsq.slipstream.persistence.User;
public abstract class FormProcessor<S extends Parameterized<S, T>, T extends Parameter<S>> {
private S parametrized;
private Map<String, T> existingParameters;
private User user;
private Form form;
public static boolean isSet(String value) {
return Parameter.hasValueSet(value);
}
public FormProcessor(User user) {
this.user = user;
}
protected Form getForm() {
return form;
}
public User getUser() {
return user;
}
public S getParametrized() {
return parametrized;
}
protected void setParametrized(S parametrized) {
this.parametrized = parametrized;
}
abstract protected S getOrCreateParameterized(String name)
throws ValidationException, NotFoundException;
public void processForm(Form form) throws BadlyFormedElementException,
SlipStreamClientException {
this.form = form;
parseForm();
parseFormParameters();
parseAuthz();
// validate();
}
protected void parseAuthz() {
return;
}
protected void parseForm() throws ValidationException, NotFoundException {
return;
}
protected void parseFormParameters() throws BadlyFormedElementException,
SlipStreamClientException {
// the params are in the form:
// - parameter--[id]--name
// - parameter--[id]--description
// - parameter--[id]--value
// ...
existingParameters = new ConcurrentHashMap<String, T>(getParametrized().getParameters());
getParametrized().getParameters().clear();
for (String paramName : form.getNames().toArray(new String[0])) {
if (isParameterName(paramName)) {
processSingleParameter(form, paramName);
}
}
}
private boolean isParameterName(String paramName) {
return paramName.startsWith("parameter-")
&& paramName.endsWith("--name");
}
protected void processSingleParameter(Form form, String paramName)
throws BadlyFormedElementException, SlipStreamClientException {
String genericPart = getGenericPart(paramName);
String name = form.getFirstValue(paramName);
String value = extractValue(form, genericPart);
String descr = extractDescription(form, genericPart);
if (!shouldProcess(name)) {
return;
}
boolean exists = (name == null) ? false : existingParameters
.containsKey(name);
if (exists) {
setExistingParameter(name, value, descr);
} else {
setNewParameter(form, genericPart, name, value);
}
}
protected boolean shouldProcess(String paramName)
throws ValidationException {
return true;
}
protected void setExistingParameter(String name, String value, String descr)
throws ValidationException {
T parameter;
parameter = existingParameters.get(name);
boolean overwrite = shouldSetValue(parameter, value);
if (overwrite) {
parameter.setValue(parseValue(value, parameter));
parameter.setDescription(descr);
}
getParametrized().setParameter(parameter);
}
private String parseValue(String value, T parameter) {
String parsed = value;
if(parameter.getType() == ParameterType.Boolean) {
parsed = Boolean.toString("on".equals(value));
}
return parsed;
}
protected void setNewParameter(Form form, String genericPart, String name,
String value) throws SlipStreamClientException, ValidationException {
T parameter;
String description = extractDescription(form, genericPart);
parameter = createParameter(name, value, description);
parameter.setMandatory(extractMandatory(form, genericPart));
parameter.setCategory(extractCategory(form, genericPart));
parameter.setType(extractType(form, genericPart));
parameter.setValue(value); // once the type is set, set the value again
if (shouldSetValue(parameter, value)) {
parametrized.setParameter(parameter);
}
}
private boolean shouldSetValue(T parameter, String value) {
return !parameter.isReadonly() || user.isSuper();
}
protected abstract T createParameter(String name, String value,
String description) throws SlipStreamClientException;
protected String getGenericPart(String paramName) {
String[] parts = paramName.split("--");
int lastSize = parts[parts.length - 1].length();
return paramName.substring(0, paramName.length() - lastSize);
}
private String extractValue(Form form, String genericPart) {
return form.getFirstValue(genericPart + "value");
}
private String extractDescription(Form form, String genericPart) {
return form.getFirstValue(genericPart + "description");
}
private boolean extractMandatory(Form form, String genericPart) {
return Boolean.parseBoolean(form.getFirstValue(genericPart
+ "mandatory"));
}
protected String extractCategory(Form form, String genericPart) {
return form.getFirstValue(genericPart + "category");
}
private ParameterType extractType(Form form, String genericPart) {
return ParameterType.valueOf(form.getFirstValue(genericPart + "type"));
}
}
| jar-service/src/main/java/com/sixsq/slipstream/user/FormProcessor.java | package com.sixsq.slipstream.user;
/*
* +=================================================================+
* SlipStream Server (WAR)
* =====
* Copyright (C) 2013 SixSq Sarl (sixsq.com)
* =====
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -=================================================================-
*/
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.restlet.data.Form;
import com.sixsq.slipstream.exceptions.BadlyFormedElementException;
import com.sixsq.slipstream.exceptions.NotFoundException;
import com.sixsq.slipstream.exceptions.SlipStreamClientException;
import com.sixsq.slipstream.exceptions.ValidationException;
import com.sixsq.slipstream.persistence.Parameter;
import com.sixsq.slipstream.persistence.ParameterType;
import com.sixsq.slipstream.persistence.Parameterized;
import com.sixsq.slipstream.persistence.User;
public abstract class FormProcessor<S extends Parameterized<S, T>, T extends Parameter<S>> {
private S parametrized;
private Map<String, T> existingParameters;
private User user;
private Form form;
public static boolean isSet(String value) {
return Parameter.hasValueSet(value);
}
public FormProcessor(User user) {
this.user = user;
}
protected Form getForm() {
return form;
}
public User getUser() {
return user;
}
public S getParametrized() {
return parametrized;
}
protected void setParametrized(S parametrized) {
this.parametrized = parametrized;
}
abstract protected S getOrCreateParameterized(String name)
throws ValidationException, NotFoundException;
public void processForm(Form form) throws BadlyFormedElementException,
SlipStreamClientException {
this.form = form;
parseForm();
parseFormParameters();
parseAuthz();
// validate();
}
protected void parseAuthz() {
return;
}
protected void parseForm() throws ValidationException, NotFoundException {
return;
}
protected void parseFormParameters() throws BadlyFormedElementException,
SlipStreamClientException {
// the params are in the form:
// - parameter--[id]--name
// - parameter--[id]--description
// - parameter--[id]--value
// ...
existingParameters = new ConcurrentHashMap<String, T>(getParametrized().getParameters());
getParametrized().getParameters().clear();
for (String paramName : form.getNames().toArray(new String[0])) {
if (isParameterName(paramName)) {
processSingleParameter(form, paramName);
}
}
}
private boolean isParameterName(String paramName) {
return paramName.startsWith("parameter-")
&& paramName.endsWith("--name");
}
protected void processSingleParameter(Form form, String paramName)
throws BadlyFormedElementException, SlipStreamClientException {
String genericPart = getGenericPart(paramName);
String name = form.getFirstValue(paramName);
String value = extractValue(form, genericPart);
if (!shouldProcess(name)) {
return;
}
boolean exists = (name == null) ? false : existingParameters
.containsKey(name);
if (exists) {
setExistingParameter(name, value);
} else {
setNewParameter(form, genericPart, name, value);
}
}
protected boolean shouldProcess(String paramName)
throws ValidationException {
return true;
}
protected void setExistingParameter(String name, String value)
throws ValidationException {
T parameter;
parameter = existingParameters.get(name);
boolean overwrite = shouldSetValue(parameter, value);
if (overwrite) {
parameter.setValue(parseValue(value, parameter));
}
getParametrized().setParameter(parameter);
}
private String parseValue(String value, T parameter) {
String parsed = value;
if(parameter.getType() == ParameterType.Boolean) {
parsed = Boolean.toString("on".equals(value));
}
return parsed;
}
protected void setNewParameter(Form form, String genericPart, String name,
String value) throws SlipStreamClientException, ValidationException {
T parameter;
String description = extractDescription(form, genericPart);
parameter = createParameter(name, value, description);
parameter.setMandatory(extractMandatory(form, genericPart));
parameter.setCategory(extractCategory(form, genericPart));
parameter.setType(extractType(form, genericPart));
parameter.setValue(value); // once the type is set, set the value again
if (shouldSetValue(parameter, value)) {
parametrized.setParameter(parameter);
}
}
private boolean shouldSetValue(T parameter, String value) {
return !parameter.isReadonly() || user.isSuper();
}
protected abstract T createParameter(String name, String value,
String description) throws SlipStreamClientException;
protected String getGenericPart(String paramName) {
String[] parts = paramName.split("--");
int lastSize = parts[parts.length - 1].length();
return paramName.substring(0, paramName.length() - lastSize);
}
private String extractValue(Form form, String genericPart) {
return form.getFirstValue(genericPart + "value");
}
private String extractDescription(Form form, String genericPart) {
return form.getFirstValue(genericPart + "description");
}
private boolean extractMandatory(Form form, String genericPart) {
return Boolean.parseBoolean(form.getFirstValue(genericPart
+ "mandatory"));
}
protected String extractCategory(Form form, String genericPart) {
return form.getFirstValue(genericPart + "category");
}
private ParameterType extractType(Form form, String genericPart) {
return ParameterType.valueOf(form.getFirstValue(genericPart + "type"));
}
}
| overwrite description of param even if exist
| jar-service/src/main/java/com/sixsq/slipstream/user/FormProcessor.java | overwrite description of param even if exist |
|
Java | apache-2.0 | 2a369066e488632e2c74024de8f5fb2e4bc072e3 | 0 | osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi | /*
* Copyright (c) OSGi Alliance (2000, 2012). All Rights Reserved.
*
* Implementation of certain elements of the OSGi
* Specification may be subject to third party intellectual property
* rights, including without limitation, patent rights (such a third party may
* or may not be a member of the OSGi Alliance). The OSGi Alliance is not responsible and shall not be
* held responsible in any manner for identifying or failing to identify any or
* all such third party intellectual property rights.
*
* This document and the information contained herein are provided on an "AS
* IS" basis and THE OSGI ALLIANCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL
* NOT INFRINGE ANY RIGHTS AND ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE OSGI ALLIANCE BE LIABLE FOR ANY
* LOSS OF PROFITS, LOSS OF BUSINESS, LOSS OF USE OF DATA, INTERRUPTION OF
* BUSINESS, OR FOR DIRECT, INDIRECT, SPECIAL OR EXEMPLARY, INCIDENTIAL,
* PUNITIVE OR CONSEQUENTIAL DAMAGES OF ANY KIND IN CONNECTION WITH THIS
* DOCUMENT OR THE INFORMATION CONTAINED HEREIN, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH LOSS OR DAMAGE.
*
* All Company, brand and product names may be trademarks that are the sole
* property of their respective owners. All rights reserved.
*/
package org.osgi.test.cases.cm.junit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.PropertyPermission;
import java.util.Set;
import junit.framework.AssertionFailedError;
import org.osgi.framework.AdminPermission;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.PackagePermission;
import org.osgi.framework.ServicePermission;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ConfigurationEvent;
import org.osgi.service.cm.ConfigurationListener;
import org.osgi.service.cm.ConfigurationPermission;
import org.osgi.service.cm.ConfigurationPlugin;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.cm.ManagedServiceFactory;
import org.osgi.service.cm.SynchronousConfigurationListener;
import org.osgi.service.permissionadmin.PermissionAdmin;
import org.osgi.service.permissionadmin.PermissionInfo;
import org.osgi.test.cases.cm.common.ConfigurationListenerImpl;
import org.osgi.test.cases.cm.common.SynchronizerImpl;
import org.osgi.test.cases.cm.shared.ModifyPid;
import org.osgi.test.cases.cm.shared.Synchronizer;
import org.osgi.test.cases.cm.shared.Util;
import org.osgi.test.support.compatibility.DefaultTestBundleControl;
import org.osgi.test.support.compatibility.Semaphore;
import org.osgi.test.support.sleep.Sleep;
/**
* @author Ikuo YAMASAKI, NTT Corporation, added many tests.
* @author Carsten Ziegeler, Adobe, added ConfigAdmin 1.5 tests
*/
public class CMControl extends DefaultTestBundleControl {
private ConfigurationAdmin cm;
private PermissionAdmin permAdmin;
private static final long SIGNAL_WAITING_TIME = Long.getLong("org.osgi.test.cases.cm.signal_waiting_time", 4000).longValue();
private List list;
private boolean permissionFlag;
private Bundle setAllPermissionBundle;
private String thisLocation = null;
private Bundle thisBundle = null;
private Set existingConfigs;
private static final String SP = ServicePermission.class.getName();
private static final String PP = PackagePermission.class.getName();
private static final String AP = AdminPermission.class.getName();
private static final String CP = ConfigurationPermission.class.getName();
private static final Dictionary propsForSync1;
static {
propsForSync1 = new Hashtable();
propsForSync1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync1");
}
private static final Dictionary propsForSync2;
static {
propsForSync2 = new Hashtable();
propsForSync2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync2");
}
private static final Dictionary propsForSync1_1;
static {
propsForSync1_1 = new Hashtable();
propsForSync1_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync1-1");
}
private static final Dictionary propsForSync1_2;
static {
propsForSync1_2 = new Hashtable();
propsForSync1_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync1-2");
}
private static final Dictionary propsForSync2_1;
static {
propsForSync2_1 = new Hashtable();
propsForSync2_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync2-1");
}
private static final Dictionary propsForSync3_1;
static {
propsForSync3_1 = new Hashtable();
propsForSync3_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync3-1");
}
private static final Dictionary propsForSync3_2;
static {
propsForSync3_2 = new Hashtable();
propsForSync3_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync3-2");
}
private static final Dictionary propsForSync4_1;
static {
propsForSync4_1 = new Hashtable();
propsForSync4_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync4-1");
}
private static final Dictionary propsForSync4_2;
static {
propsForSync4_2 = new Hashtable();
propsForSync4_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync4-2");
}
private static final Dictionary propsForSyncF1_1;
static {
propsForSyncF1_1 = new Hashtable();
propsForSyncF1_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF1-1");
}
private static final Dictionary propsForSyncF1_2;
static {
propsForSyncF1_2 = new Hashtable();
propsForSyncF1_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF1-2");
}
private static final Dictionary propsForSyncF2_1;
static {
propsForSyncF2_1 = new Hashtable();
propsForSyncF2_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF2-1");
}
private static final Dictionary propsForSyncF3_1;
static {
propsForSyncF3_1 = new Hashtable();
propsForSyncF3_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF3-1");
}
private static final Dictionary propsForSyncF3_2;
static {
propsForSyncF3_2 = new Hashtable();
propsForSyncF3_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF3-2");
}
private static final Dictionary propsForSyncT5_1;
static {
propsForSyncT5_1 = new Hashtable();
propsForSyncT5_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncT5-1");
}
private static final Dictionary propsForSyncT6_1;
static {
propsForSyncT6_1 = new Hashtable();
propsForSyncT6_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncT6-1");
}
private static final String neverlandLocation = "http://neverneverland/";
protected void setUp() throws Exception {
// printoutBundleList();
assignCm();
// populate the created configurations so that
// listConfigurations can return these configurations
list = new ArrayList(5);
if (System.getSecurityManager() != null) {
permAdmin = (PermissionAdmin) getService(PermissionAdmin.class);
setAllPermissionBundle = getContext().installBundle(
getWebServer() + "setallpermission.jar");
thisBundle = getContext().getBundle();
thisLocation = thisBundle.getLocation();
} else {
permissionFlag = true;
}
// existing configurations
Configuration[] configs = cm.listConfigurations(null);
existingConfigs = new HashSet();
if (configs != null) {
for (int i = 0; i < configs.length; i++) {
Configuration config = configs[i];
// log("setUp() -- Register pre-existing config " + config.getPid());
existingConfigs.add(config.getPid());
}
}
}
protected void tearDown() throws Exception {
resetPermissions();
cleanCM(existingConfigs);
if (this.setAllPermissionBundle != null) {
this.setAllPermissionBundle.uninstall();
this.setAllPermissionBundle = null;
}
if (permAdmin != null)
ungetService(permAdmin);
list = null;
unregisterAllServices();
ungetService(cm);
System.out.println("tearDown()");
// this.printoutBundleList();
}
private void resetPermissions() throws BundleException {
if (permAdmin == null)
return;
try {
if (this.setAllPermissionBundle == null)
this.setAllPermissionBundle = getContext().installBundle(
getWebServer() + "setallpermission.jar");
this.setAllPermissionBundle.start();
this.setAllPermissionBundle.stop();
} catch (BundleException e) {
Exception ise = new IllegalStateException(
"fail to install or start setallpermission bundle.");
ise.initCause(e);
throw e;
}
this.printoutPermissions();
}
private void printoutPermissions() {
if (permAdmin == null)
return;
String[] locations = this.permAdmin.getLocations();
if (locations != null)
for (int i = 0; i < locations.length; i++) {
System.out.println("locations[" + i + "]=" + locations[i]);
PermissionInfo[] pInfos = this.permAdmin
.getPermissions(locations[i]);
for (int j = 0; j < pInfos.length; j++) {
System.out.println("\t" + pInfos[j]);
}
}
PermissionInfo[] pInfos = this.permAdmin.getDefaultPermissions();
if (pInfos == null)
System.out.println("default permission=null");
else {
System.out.println("default permission=");
for (int j = 0; j < pInfos.length; j++) {
System.out.println("\t" + pInfos[j]);
}
}
}
private void printoutBundleList() {
Bundle[] bundles = this.getContext().getBundles();
for (int i = 0; i < bundles.length; i++) {
System.out.println("bundles[" + i + "]="
+ bundles[i].getSymbolicName() + "["
+ bundles[i].getState() + "]");
// if (bundles[i].getState() != Bundle.ACTIVE)
// System.exit(0);
}
}
private void setBundlePermission(Bundle b, List list) {
if (permAdmin == null)
return;
PermissionInfo[] pis = new PermissionInfo[list.size()];
pis = (PermissionInfo[]) list.toArray(pis);
permAdmin.setPermissions(b.getLocation(), pis);
this.printoutPermissions();
}
private List getBundlePermission(Bundle b) {
if (permAdmin == null) return null;
PermissionInfo[] pis = permAdmin.getPermissions(b.getLocation());
return Arrays.asList(pis);
}
private void add(List permissionsInfos, String clazz, String name,
String actions) {
permissionsInfos.add(new PermissionInfo(clazz, name, actions));
}
/** *** Test methods **** */
/**
* Test that the methods throws IllegalStateException when operating on a
* deleted Configuration
*
* @spec Configuration.delete()
* @spec Configuration.getBundleLocation()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getPid()
* @spec Configuration.getProperties()
* @spec Configuration.setBundleLocation(String)
*/
public void testDeletedConfiguration() throws Exception {
String pid = Util.createPid();
Configuration conf = null;
/* Get a brand new configuration and delete it. */
conf = cm.getConfiguration(pid);
conf.delete();
/*
* A list of all methodcalls that should be made to the deleted
* Configuration object
*/
MethodCall[] methods = {
new MethodCall(Configuration.class, "delete"),
new MethodCall(Configuration.class, "getBundleLocation"),
new MethodCall(Configuration.class, "getFactoryPid"),
new MethodCall(Configuration.class, "getPid"),
new MethodCall(Configuration.class, "getProperties"),
new MethodCall(Configuration.class, "getChangeCount"),
new MethodCall(Configuration.class, "setBundleLocation",
String.class, "somelocation"),
new MethodCall(Configuration.class, "update"),
new MethodCall(Configuration.class, "update", Dictionary.class,
new Hashtable()) };
/* Make all the methodcalls in the list */
for (int i = 0; i < methods.length; i++) {
try {
/* Call the method on the Configuration object */
methods[i].invoke(conf);
/*
* In this case it should always throw an IllegalStateException
* so if we end up here, somethings wrong
*/
failException(methods[i].getName(), IllegalStateException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(methods[i].getName(),
IllegalStateException.class, e);
}
}
}
/**
* TODO comments
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec ConfigurationAdmin.getConfiguration(String,String)
* @spec Configuration.getBundleLocation()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getPid()
* @spec Configuration.getProperties()
* @spec Configuration.setBundleLocation(String)
*
* @throws Exception
*/
public void testGetConfiguration() throws Exception {
this.setInappropriatePermission();
String pid = Util.createPid();
String thisLocation = getLocation();
Configuration conf = null;
/* Get a brand new configuration */
conf = cm.getConfiguration(pid);
checkConfiguration(conf, "A new Configuration object", pid,
thisLocation);
/* Get location of the configuration */
/* must fail because of inappropriate Permission. */
String message = "try to get location without appropriate ConfigurationPermission.";
try {
conf.getBundleLocation();
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null) failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null) fail("Security is not enabled", e);
}
/* Get the configuration again (should be exactly the same) */
conf = cm.getConfiguration(pid);
checkConfiguration(conf, "The same Configuration object", pid,
thisLocation);
/*
* Change the location of the bundle and then get the Configuration
* again. The location should not have been touched.
*/
/* must fail because of inappropriate Permission. */
message = "try to set location without appropriate ConfigurationPermission.";
try {
conf.setBundleLocation(neverlandLocation);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
conf.setBundleLocation(neverlandLocation);
conf = cm.getConfiguration(pid);
assertEquals("Location Neverland", neverlandLocation,
this.getBundleLocationForCompare(conf));
this.setInappropriatePermission();
/* must fail because of inappropriate Permission. */
message = "try to get configuration whose location is different from the caller bundle without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
/* Clean up */
conf.delete();
}
/**
* TODO comments
*
* @spec ConfigurationAdmin.getConfiguration(String,String)
* @spec Configuration.getBundleLocation()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.getProperties()
*
* @throws Exception
*/
public void testGetConfigurationWithLocation() throws Exception {
final String pid1 = Util.createPid("1");
final String pid2 = Util.createPid("2");
final String pid3 = Util.createPid("3");
// final String thisLocation = getLocation();
Configuration conf = null;
this.printoutPermissions();
this.setInappropriatePermission();
/*
* Without appropriate ConfigurationPermission, Get a brand new
* configuration.
*/
String message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid1, thisLocation);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
fail("Throwable must not be thrown for Configuration#getBundleLocation()",
e);
}
/*
* Without appropriate ConfigurationPermission, Get an existing
* configuration with thisLocation, but specify the location (which
* should then be ignored).
*/
// TODO Change the explanation
message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid1, neverlandLocation);
// checkConfiguration(conf, "The same Configuration object",
// pid1,thisLocation);
fail("SecurityException must be thrown because cm must check the set location.");
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// fail("Throwable must not be thrown because the configuring bundle has implicit CP for thisLocation",e);
}
conf.delete();
this.setInappropriatePermission();
/*
* Without appropriate ConfigurationPermission, Get a brand new
* configuration with a specified location
*/
message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid2, neverlandLocation);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
/* Get a brand new configuration with a specified location */
conf = cm.getConfiguration(pid2, neverlandLocation);
checkConfiguration(conf, "A new Configuration object", pid2,
neverlandLocation);
conf.delete();
this.setInappropriatePermission();
/*
* Without appropriate ConfigurationPermission, Get a brand new
* configuration with no location
*/
message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid3, null);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
/* Get a brand new configuration with no location */
conf = cm.getConfiguration(pid3, null);
checkConfiguration(conf, "A new Configuration object", pid3, null);
conf.delete();
}
/**
* TODO comments
*
* @spec ConfigurationAdmin.getConfiguration(String,String)
* @spec Configuration.getBundleLocation()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.getProperties()
*
* @throws Exception
*/
public void testConfigurationWithNullLocation() throws Exception {
final String bundlePid = Util.createPid("bundle1Pid");
final String thisLocation = getLocation();
Configuration conf = null;
this.setInappropriatePermission();
/*
* Without appropriate ConfigurationPermission, Get a brand new
* configuration with no location
*/
String message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(bundlePid, null);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
/* Get a brand new configuration with no location */
conf = cm.getConfiguration(bundlePid, null);
checkConfiguration(conf, "A new Configuration object", bundlePid, null);
Dictionary props = new Hashtable();
props.put("StringKey", getName());
conf.update(props);
/*
* Get existing Configuration with neverland location, which should be
* ignored
*/
Configuration conf3 = cm.getConfiguration(bundlePid, neverlandLocation);
assertEquals("Pid", bundlePid, conf3.getPid());
assertNull("FactoryPid", conf3.getFactoryPid());
assertNull("Location", this.getBundleLocationForCompare(conf3));
assertEquals("The same Confiuration props", getName(), conf3
.getProperties().get("StringKey"));
System.out.println("###########################"
+ conf3.getBundleLocation());
// System.out.println("###########################"+cm.getConfiguration(bundlePid).getBundleLocation());
this.setInappropriatePermission();
/* Get location of the configuration with null location */
/* must fail because of inappropriate Permission. */
message = "try to get location without appropriate ConfigurationPermission.";
try {
conf.getBundleLocation();
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
message = "try to get configuration with null location without appropriate ConfigurationPermission.";
/*
* try { Configuration conf4 = cm.getConfiguration(bundlePid);
*
* A SecurityException should have been thrown if security is enabled
*
* if (System.getSecurityManager() != null) failException(message,
* SecurityException.class); } catch (AssertionFailedError e) { throw e;
* } catch (Throwable e) { Check that we got the correct exception
* assertException(message, SecurityException.class, e);
*
* A SecurityException should not have been thrown if security is not
* enabled
*
* if (System.getSecurityManager() == null)
* fail("Security is not enabled", e); }
*/
Configuration conf4 = cm.getConfiguration(bundlePid);
/* location MUST be changed to the callers bundle's location. */
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf4));
/* In order to get Location, appropriate permission is required. */
this.setAppropriatePermission();
cm.getConfiguration(bundlePid).setBundleLocation(null);
Configuration conf5 = cm.getConfiguration(bundlePid);
/* location MUST be changed to the callers bundle's location. */
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf5));
// this.setAppropriatePermission();
// conf3 = cm.getConfiguration(pid3);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf3));
this.setInappropriatePermission();
/* Set location of the configuration to null location */
/* must fail because of inappropriate Permission. */
message = "try to set location to null without appropriate ConfigurationPermission.";
try {
conf.setBundleLocation(null);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
conf.setBundleLocation(null);
this.setInappropriatePermission();
/* Set location of the configuration with null location to others */
/* must fail because of inappropriate Permission. */
message = "try to set location to null without appropriate ConfigurationPermission.";
try {
conf.setBundleLocation(thisLocation);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
try {
conf.setBundleLocation(neverlandLocation);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
conf.delete();
}
/**
* Test the change counter.
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testChangeCount() throws Exception {
trace("Testing change count...");
// create config with pid
trace("Create test configuration");
final String pid = "test_ca_counter_" + ConfigurationListenerImpl.LISTENER_PID_SUFFIX;
final Configuration config = this.cm.getConfiguration(pid);
final long startCount = config.getChangeCount();
// register sync and async listener for change updates
trace("Create and register configuration listeners");
// list to check whether the sync listener is called
final List events = new ArrayList();
final SynchronousConfigurationListener scl = new SynchronousConfigurationListener() {
// the sync listener is called during the update method and the
// change count should of course already be updated.
public void configurationEvent(final ConfigurationEvent event) {
if (event.getPid() != null
&& event.getPid().endsWith(ConfigurationListenerImpl.LISTENER_PID_SUFFIX)
&& event.getFactoryPid() == null) {
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
assertTrue("Expect second change count to be higher than " + startCount + " : " + config.getChangeCount(),
config.getChangeCount() > startCount);
events.add(event);
}
}
};
ConfigurationListenerImpl cl = null;
final SynchronizerImpl synchronizer = new SynchronizerImpl();
this.registerService(SynchronousConfigurationListener.class.getName(), scl, null);
try {
cl = createConfigurationListener(synchronizer);
// update config with properties
config.update(new Hashtable(){{put("x", "x");}});
assertTrue("Sync listener not called.", events.size() == 1);
assertTrue("Expect second change count to be higher than " + startCount + " : " + config.getChangeCount(),
config.getChangeCount() > startCount);
trace("Wait until the ConfigurationListener has gotten the update");
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
trace("Checking configuration event");
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType());
// reget configuration and check count
trace("Checking regetting configuration");
final Configuration configNew = this.cm.getConfiguration(pid);
assertEquals("Configuration change count shouldn't have changed", config.getChangeCount(), configNew.getChangeCount());
assertTrue("Expect second change count to be higher than " + startCount + " : " + configNew.getChangeCount(),
configNew.getChangeCount() > startCount);
trace("Testing change count...finished");
} finally {
// clean up
if ( cl != null ) {
removeConfigurationListener(cl);
}
this.unregisterService(scl);
config.delete();
}
}
/**
* Test the change counter for factory configuration
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testChangeCountFactory() throws Exception {
trace("Testing change count factory...");
// create config with pid
trace("Create test configuration");
final String factoryPid = "test_ca_counter_factory_" + ConfigurationListenerImpl.LISTENER_PID_SUFFIX;
final Configuration config = this.cm.createFactoryConfiguration(factoryPid);
final String pid = config.getPid();
final long startCount = config.getChangeCount();
// register sync and async listener for change updates
trace("Create and register configuration listeners");
// list to check whether the sync listener is called
final List events = new ArrayList();
final SynchronousConfigurationListener scl = new SynchronousConfigurationListener() {
// the sync listener is called during the update method and the
// change count should of course already be updated.
public void configurationEvent(final ConfigurationEvent event) {
if (event.getPid() != null
&& event.getFactoryPid().endsWith(ConfigurationListenerImpl.LISTENER_PID_SUFFIX)) {
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
assertTrue("Expect second change count to be higher than " + startCount + " : " + config.getChangeCount(),
config.getChangeCount() > startCount);
events.add(event);
}
}
};
ConfigurationListenerImpl cl = null;
final SynchronizerImpl synchronizer = new SynchronizerImpl();
this.registerService(SynchronousConfigurationListener.class.getName(), scl, null);
try {
cl = createConfigurationListener(synchronizer);
// update config with properties
config.update(new Hashtable(){{put("x", "x");}});
assertTrue("Sync listener not called.", events.size() == 1);
assertTrue("Expect second change count to be higher than " + startCount + " : " + config.getChangeCount(),
config.getChangeCount() > startCount);
trace("Wait until the ConfigurationListener has gotten the update");
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
trace("Checking configuration event");
assertEquals("Config event factory pid match", factoryPid, cl.getFactoryPid());
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType());
// reget configuration and check count
trace("Checking regetting configuration");
final Configuration[] cfs = cm.listConfigurations( "(" + ConfigurationAdmin.SERVICE_FACTORYPID + "="
+ factoryPid + ")" );
final Configuration configNew = cfs[0];
assertEquals("Configuration change count shouldn't have changed", config.getChangeCount(), configNew.getChangeCount());
assertTrue("Expect second change count to be higher than " + startCount + " : " + configNew.getChangeCount(),
configNew.getChangeCount() > startCount);
trace("Testing change count...finished");
} finally {
// clean up
if ( cl != null ) {
removeConfigurationListener(cl);
}
this.unregisterService(scl);
config.delete();
}
}
/**
* Test sync listener.
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testSyncListener() throws Exception {
trace("Testing sync listener...");
trace("Create and register sync configuration listeners");
// List of events
final List events = new ArrayList();
// Thread check
final Thread callerThread = Thread.currentThread();
final SynchronousConfigurationListener scl = new SynchronousConfigurationListener() {
// the sync listener is called during the update method and the
// change count should of course already be updated.
public void configurationEvent(final ConfigurationEvent event) {
if (event.getPid() != null
&& event.getPid().endsWith(ConfigurationListenerImpl.LISTENER_PID_SUFFIX)
&& event.getFactoryPid() == null) {
// check thread
if ( Thread.currentThread() != callerThread ) {
fail("Method is not called in sync.");
}
events.add(event);
}
}
};
this.registerService(SynchronousConfigurationListener.class.getName(), scl, null);
Configuration config = null;
try {
// create config with pid
trace("Create test configuration");
final String pid = "test_sync_config_" + ConfigurationListenerImpl.LISTENER_PID_SUFFIX;
config = this.cm.getConfiguration(pid);
config.update(new Hashtable(){{put("y", "y");}});
assertEquals("No event received: " + events, 1, events.size());
ConfigurationEvent event = (ConfigurationEvent)events.get(0);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
// update config
config.update(new Hashtable(){{put("x", "x");}});
assertEquals("No event received", 2, events.size());
event = (ConfigurationEvent)events.get(1);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
// update location
config.setBundleLocation("location");
assertEquals("No event received", 3, events.size());
event = (ConfigurationEvent)events.get(2);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_LOCATION_CHANGED, event.getType());
// delete config
config.delete();
config = null;
assertEquals("No event received", 4, events.size());
event = (ConfigurationEvent)events.get(3);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, event.getType());
} finally {
this.unregisterService(scl);
if ( config != null ) {
config.delete();
}
}
trace("Testing sync listener...finished");
}
/**
* Test sync listener for factory config.
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testSyncListenerFactory() throws Exception {
trace("Testing sync listener...");
trace("Create and register sync configuration listeners");
// List of events
final List events = new ArrayList();
// Thread check
final Thread callerThread = Thread.currentThread();
final SynchronousConfigurationListener scl = new SynchronousConfigurationListener() {
// the sync listener is called during the update method and the
// change count should of course already be updated.
public void configurationEvent(final ConfigurationEvent event) {
if (event.getPid() != null
&& event.getFactoryPid().endsWith(ConfigurationListenerImpl.LISTENER_PID_SUFFIX)) {
// check thread
if ( Thread.currentThread() != callerThread ) {
fail("Method is not called in sync.");
}
events.add(event);
}
}
};
this.registerService(SynchronousConfigurationListener.class.getName(), scl, null);
Configuration config = null;
try {
// create config with pid
trace("Create test configuration");
final String factoryPid = "test_sync_config_factory_" + ConfigurationListenerImpl.LISTENER_PID_SUFFIX;
config = this.cm.createFactoryConfiguration(factoryPid);
final String pid = config.getPid();
config.update(new Hashtable(){{put("y", "y");}});
assertEquals("No event received: " + events, 1, events.size());
ConfigurationEvent event = (ConfigurationEvent)events.get(0);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
// update config
config.update(new Hashtable(){{put("x", "x");}});
assertEquals("No event received", 2, events.size());
event = (ConfigurationEvent)events.get(1);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
// update location
config.setBundleLocation("location");
assertEquals("No event received", 3, events.size());
event = (ConfigurationEvent)events.get(2);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_LOCATION_CHANGED, event.getType());
// delete config
config.delete();
config = null;
assertEquals("No event received", 4, events.size());
event = (ConfigurationEvent)events.get(3);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, event.getType());
} finally {
this.unregisterService(scl);
if ( config != null ) {
config.delete();
}
}
trace("Testing sync listener...finished");
}
/**
* Test targeted pids
* Create configs for the same pid, each new config is either more "specific" than
* the previous one or "invalid"
* Check if the new config is either bound or ignored
* Then delete configs in reverse order and check if either nothing is happening
* ("invalid" configs) or rebound to a previous config happens.
*
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testTargetedPid() throws Exception {
trace("Testing targeted pids...");
final Bundle bundleT5 = getContext().installBundle(
getWebServer() + "bundleT5.jar");
final Bundle bundleT6 = getContext().installBundle(
getWebServer() + "bundleT6.jar");
final String pidBase = Util.createPid("pid_targeted1");
// create a list of configurations
// the first char is a "bitset":
// if bit 1 is set, T5 should get the config
// if bit 2 is set, T6 should get the config
// so: 0 : no delivery, 1 : T5, 2: T6, 3: T5 + T6
final String[] pids = new String[] {
"3" + pidBase,
"1" + pidBase + "|" + bundleT5.getSymbolicName(),
"2" + pidBase + "|" + bundleT6.getSymbolicName(),
"0" + pidBase + "|Not" + bundleT5.getSymbolicName(),
"1" + pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString(),
"2" + pidBase + "|" + bundleT6.getSymbolicName() + "|" + bundleT6.getHeaders().get(Constants.BUNDLE_VERSION).toString(),
"0" + pidBase + "|" + bundleT5.getSymbolicName() + "|555.555.555.Not",
"0" + pidBase + "|" + bundleT6.getSymbolicName() + "|555.555.555.Not",
"1" + pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT5.getLocation(),
"2" + pidBase + "|" + bundleT6.getSymbolicName() + "|" + bundleT6.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT6.getLocation(),
"0" + pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT5.getLocation() + "Not",
"0" + pidBase + "|" + bundleT6.getSymbolicName() + "|" + bundleT6.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT6.getLocation() + "Not"
};
final List list = new ArrayList(5);
final List configs = new ArrayList();
try {
final SynchronizerImpl sync1_1 = new SynchronizerImpl("T5-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncT5_1));
final SynchronizerImpl sync2_1 = new SynchronizerImpl("T6-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncT6_1));
this.startTargetBundle(bundleT5);
this.setCPtoBundle("*", ConfigurationPermission.TARGET, bundleT5, false);
this.startTargetBundle(bundleT6);
this.setCPtoBundle("*", ConfigurationPermission.TARGET, bundleT6, false);
trace("Wait for signal.");
int count1_1 = 0, count2_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
// let's create some configurations
String previousKeyT5 = null, previousKeyT6 = null;
for(int i=0; i<pids.length; i++) {
// key contains marker at char 0 + pid
final String key = pids[i];
final String pid = key.substring(1);
trace("Creating config " + pid);
final Configuration c = this.cm.getConfiguration(pid, "?*");
configs.add(c);
final String propPreviousKeyT5 = previousKeyT5;
final String propPreviousKeyT6 = previousKeyT6;
c.update(new Hashtable(){
{
put("test", key);
if ( propPreviousKeyT5 != null ) {
put("previousT5", propPreviousKeyT5);
}
if ( propPreviousKeyT6 != null ) {
put("previousT6", propPreviousKeyT6);
}
}
});
// check T5
final char deliveryMarker = key.charAt(0);
if ( deliveryMarker == '0' || deliveryMarker == '2') {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
assertEquals("Pid is wrong", key, sync1_1.getProps().get("test"));
previousKeyT5 = key;
}
// check T6
if ( deliveryMarker == '0' || deliveryMarker == '1') {
assertNoCallback(sync2_1, count2_1);
} else {
count2_1 = assertCallback(sync2_1, count2_1);
assertEquals("Pid is wrong", key, sync2_1.getProps().get("test"));
previousKeyT6 = key;
}
}
// we now delete the configuration in reverse order
while ( configs.size() > 0 ) {
final Configuration c = (Configuration) configs.remove(configs.size() - 1);
final String key = (String) c.getProperties().get("test");
previousKeyT5 = (String) c.getProperties().get("previousT5");
previousKeyT6 = (String) c.getProperties().get("previousT6");
c.delete();
// check T5
final char deliveryMarker = key.charAt(0);
if ( deliveryMarker == '0' || deliveryMarker == '2') {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
if ( configs.size() == 0 ) {
// removed last config, so this is a delete
assertNull(sync1_1.getProps());
} else {
// this is an update = downgrade to a previous config
assertNotNull(sync1_1.getProps());
final String newPid = (String) sync1_1.getProps().get("test");
assertEquals("Pid is wrong", previousKeyT5, newPid);
}
}
// check T6
if ( deliveryMarker == '0' || deliveryMarker == '1') {
assertNoCallback(sync2_1, count2_1);
} else {
count2_1 = assertCallback(sync2_1, count2_1);
if ( configs.size() == 0 ) {
// removed last config, so this is a delete
assertNull(sync2_1.getProps());
} else {
// this is an update = downgrade to a previous config
assertNotNull(sync2_1.getProps());
final String newPid = (String) sync2_1.getProps().get("test");
assertEquals("Pid is wrong", previousKeyT6, newPid);
}
}
}
} finally {
cleanUpForCallbackTest(bundleT5, bundleT6, null, null, list);
Iterator i = configs.iterator();
while ( i.hasNext() ) {
final Configuration c = (Configuration) i.next();
c.delete();
}
}
trace("Testing targeted pids...finished");
}
/**
* Test targeted factory pids
*
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testTargetedFactoryPid() throws Exception {
trace("Testing targeted factory pids...");
final Bundle bundleT5 = getContext().installBundle(
getWebServer() + "bundleT5.jar");
final String pidBase = Util.createPid("pid_targeted3");
final String[] pids = new String[] {
pidBase,
pidBase + "|" + bundleT5.getSymbolicName(),
pidBase + "|Not" + bundleT5.getSymbolicName(),
pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString(),
pidBase + "|" + bundleT5.getSymbolicName() + "|555.555.555.Not",
pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT5.getLocation(),
pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT5.getLocation() + "Not"
};
final List list = new ArrayList(5);
final List configs = new ArrayList();
try {
final SynchronizerImpl sync1_1 = new SynchronizerImpl("T5-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncT5_1));
this.startTargetBundle(bundleT5);
this.setCPtoBundle("*", ConfigurationPermission.TARGET, bundleT5, false);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
// let's create some configurations
for(int i=0; i<pids.length; i++) {
final String factoryPid = pids[i];
trace("Creating factory config " + factoryPid);
final Configuration c = this.cm.createFactoryConfiguration(factoryPid, null);
configs.add(c);
c.update(new Hashtable(){{
put("test", c.getPid());
put("factoryPid", factoryPid);
}});
if ( factoryPid.indexOf("Not") != -1 ) {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
assertEquals("Pid is wrong", c.getPid(), sync1_1.getProps().get("test"));
}
}
// now delete them - order doesn't really matter, but we use reverse order anyway
while ( configs.size() > 0 ) {
final Configuration c = (Configuration) configs.remove(configs.size() - 1);
final String pid = (String) c.getProperties().get("test");
final String factoryPid = (String) c.getProperties().get("factoryPid");
c.delete();
if ( factoryPid.indexOf("Not") != -1 ) {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
assertEquals("Pid is wrong", pid, sync1_1.getProps().get("test"));
assertEquals("Pid is not delete", Boolean.TRUE, sync1_1.getProps().get("_deleted_"));
}
}
} finally {
cleanUpForCallbackTest(bundleT5, null, null, null, list);
Iterator i = configs.iterator();
while ( i.hasNext() ) {
final Configuration c = (Configuration) i.next();
c.delete();
}
}
trace("Testing targeted factory pids...finished");
}
/**
* Test targeted pids
* Use a pid with a '|' .
*
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testNegativeTargetedPid() throws Exception {
trace("Testing targeted pids...");
final Bundle bundleT5 = getContext().installBundle(
getWebServer() + "bundleT5.jar");
final String pid1 = Util.createPid("pid");
final String pid2 = Util.createPid("pid|targeted2");
final String[] pids = new String[] {pid1, pid2};
final List list = new ArrayList(5);
final List configs = new ArrayList();
try {
final SynchronizerImpl sync1_1 = new SynchronizerImpl("T5-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncT5_1));
this.startTargetBundle(bundleT5);
this.setCPtoBundle("*", ConfigurationPermission.TARGET, bundleT5, false);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
// let's create some configurations
for(int i=0; i<pids.length; i++) {
final String pid = pids[i];
trace("Creating config " + pid);
final Configuration c = this.cm.getConfiguration(pid, null);
configs.add(c);
c.update(new Hashtable(){
{
put("test", pid);
}
});
if ( pid.indexOf("|") == -1 ) {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
assertEquals("Pid is wrong", pid, sync1_1.getProps().get("test"));
}
}
// we now delete the configuration in reverse order
while ( configs.size() > 0 ) {
final Configuration c = (Configuration) configs.remove(configs.size() - 1);
final String pid = (String) c.getProperties().get("test");
c.delete();
if ( pid.indexOf("|") == -1 ) {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
// remove, so no rebind
assertNull(sync1_1.getProps());
}
}
} finally {
cleanUpForCallbackTest(bundleT5, null, null, null, list);
Iterator i = configs.iterator();
while ( i.hasNext() ) {
final Configuration c = (Configuration) i.next();
c.delete();
}
}
trace("Testing targeted pids...finished");
}
/**
* Dynamic binding( configuration with null location and ManagedService)
*
* @spec ConfigurationAdmin.getConfiguration(String,String)
* @spec Configuration.getBundleLocation()
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.getProperties()
*
* @throws Exception
*/
public void testDynamicBinding() throws Exception {
Bundle bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
final String bundlePid = Util.createPid("bundlePid1");
Configuration conf = null;
ServiceRegistration reg = null;
Dictionary props = null;
/*
* 1. created newly with non-null location and after set to null. After
* that, ManagedService is registered.
*/
trace("############ 1 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, bundle1.getLocation());
props = new Hashtable();
props.put("StringKey", getName() + "-1");
conf.update(props);
conf.setBundleLocation(null);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
bundle1.stop();
assertEquals("Dynamic binding(STOPPED). Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
/*
* After the dynamically bound bundle has been uninstalled, the
* location must be reset to null.
*/
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
assertNull("Dynamic binding(UNINSTALLED)", conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
// conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/* 2. created newly with null location.(with properties) */
trace("############ 2 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
/* props is set. */
props = new Hashtable();
props.put("StringKey", getName() + "-2");
conf.update(props);
reg = null;
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
bundle1.stop();
assertEquals("Dynamic binding(STOPPED).Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
assertNull("Dynamic binding(UNINSTALLED)", conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
// conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/* 3. created newly with null location. (no properties) */
trace("############ 3 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
bundle1.stop();
assertEquals("Dynamic binding(STOPPED).Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
assertNull("Dynamic binding(UNINSTALLED)", conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
// conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* 4. created newly with null location and dynamic bound. Then
* explicitly set location. --> never dynamically unbound - bound
* anymore.
*/
trace("############ 4 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
props = new Hashtable();
props.put("StringKey", getName() + "-4");
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
conf.setBundleLocation(bundle1.getLocation());
bundle1.stop();
assertEquals("No more Dynamic binding(STOPPED). Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
assertEquals("No more Dynamic binding(UNINSTALLED)",
bundle1.getLocation(), conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
// conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* 5. dynamic binding and cm restart 1 (with properties).
*/
/**
* (a)install test bundle. (b)configure test bundle. (c)stop
* configuration admin service. (d)start configuration admin service
*
* ==> configuration is still bound to the target bundle
*/
trace("############ 5 testDynamicBinding()");
Bundle cmBundle = null;
try {
conf = cm.getConfiguration(bundlePid, null);
props = new Hashtable();
props.put("StringKey", getName() + "-5");
conf.update(props);
reg = null;
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue("ManagedService MUST be called back.", calledback);
bundle1.stop();
restartCM();
Sleep.sleep(SIGNAL_WAITING_TIME * 2);
Configuration[] confs = cm.listConfigurations(null);
assertNotNull("confs must NOT be empty:", confs);
assertEquals("confs.length must be one", 1, confs.length-existingConfigs.size());
for (int i = 0; i < confs.length; i++) {
conf = confs[i];
if (!existingConfigs.contains(conf.getPid())) {
trace("confs[" + i + "].getBundleLocation()=" + confs[i].getBundleLocation());
assertEquals("Dynamic binding(UNINSTALLED):confs[" + i
+ "].getBundleLocation() must be the target bundle", bundle1.getLocation(),
confs[i].getBundleLocation());
}
}
conf = cm.getConfiguration(bundlePid);
assertEquals(
"Restarted CM: Must be still bound to the target bundle.",
bundle1.getLocation(), conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* 6. dynamic binding and cm restart 2(with properties).
*/
/**
* (a)install test bundle. (b)configure test bundle. (c)stop
* configuration admin service. (d)uninstall test bundle. (e)start
* configuration admin service
*
* ==> configuration is still bound to the uninstalled bundle
*/
trace("############ 6 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
props = new Hashtable();
props.put("StringKey", getName() + "-6");
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
cmBundle = stopCmBundle();
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
bundle1.stop();
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
Sleep.sleep(SIGNAL_WAITING_TIME * 2);
Configuration[] confs = cm.listConfigurations(null);
assertNotNull("confs must NOT be empty:", confs);
assertEquals("confs.length must be one", 1, confs.length - existingConfigs.size());
for (int i = 0; i < confs.length; i++) {
conf = confs[i];
if (!existingConfigs.contains(conf.getPid())) {
trace("confs[" + i + "].getBundleLocation()=" + confs[i].getBundleLocation());
assertEquals("Dynamic binding(UNINSTALLED):confs[" + i + "].getBundleLocation() must be null",
null, confs[i].getBundleLocation());
}
}
conf = cm.getConfiguration(bundlePid);
assertEquals("Dynamic binding(UNINSTALLED): Must be Re-bound",
getContext().getBundle().getLocation(),
conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* 7. dynamic binding and cm restart 2 (with no properties).
*/
/**
* (a)install test bundle. (b)configure test bundle. (c)stop
* configuration admin service. (d)uninstall test bundle. (e)start
* configuration admin service
*
* ==> configuration is still bound to the uninstalled bundle
*/
trace("############ 7 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
// props = new Hashtable();
// props.put("StringKey", getName()+"-7");
// conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
cmBundle = stopCmBundle();
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
bundle1.stop();
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
Sleep.sleep(SIGNAL_WAITING_TIME * 2);
conf = cm.getConfiguration(bundlePid, null);
assertEquals("Dynamic binding(UNINSTALLED): Must be reset to null",
null, conf.getBundleLocation());
conf = cm.getConfiguration(bundlePid);
assertEquals("Dynamic binding(UNINSTALLED): Must be Re-bound",
getContext().getBundle().getLocation(),
conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* [In Progress] 8. After created newly with non-null location and
* ManagedService is registered, the location is set to null. What
* happens ?
*/
trace("############ 8 testDynamicBinding()");
ServiceRegistration reg2 = null;
Bundle bundle2 = null;
try {
conf = cm.getConfiguration(bundlePid, getWebServer()
+ "targetb1.jar");
props = new Hashtable();
props.put("StringKey", getName() + "-8");
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl("ID1");
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
conf.setBundleLocation(null);
trace("Wait for signal.");
// calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
// assertFalse("ManagedService MUST NOT be called back.",
// calledback);
// assertEquals("Must be still bound to the target bundle.",
// bundle1.getLocation(), conf.getBundleLocation());
// TODO: check if the unbound once (updated(null) is called)
// and bound againg (updated(props) is called ).
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count++);
assertTrue("ManagedService MUST be called back.", calledback);
conf.update(props);
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count++);
assertTrue("ManagedService MUST be called back.", calledback);
assertEquals("Must be bound to the target bundle. again.",
bundle1.getLocation(), conf.getBundleLocation());
bundle2 = getContext().installBundle(
getWebServer() + "targetb2.jar");
SynchronizerImpl sync2 = new SynchronizerImpl("ID2");
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
this.startTargetBundle(bundle2);
trace("Wait for signal.");
int count2 = 0;
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
//assertFalse(
// "ManagedService MUST NOT be called back in case conf has no properties.",
// calledback2);
assertTrue(
"ManagedService MUST be called back with null property.",
calledback2);
bundle1.stop();
assertEquals("Dynamic binding(STOPPED). Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
calledback = sync2.waitForSignal(SIGNAL_WAITING_TIME, count2 + 1);
assertFalse("ManagedService2 MUST NOT be called back.", calledback);
bundle1.uninstall();
trace("Dynamic binding(UNINSTALLED). Wait for a while.");
calledback2 = sync2
.waitForSignal(SIGNAL_WAITING_TIME * 2, ++count2);
assertTrue("ManagedService2 MUST be called back.", calledback2);
assertEquals("Dynamic binding(UNINSTALLED). Wait for a while.", bundle2.getLocation(),
conf.getBundleLocation());
props.put("StringKey", "stringvalue2");
conf.update(props);
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService MUST be called back.", calledback2);
conf.delete();
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService MUST be called back.", calledback2);
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertFalse("ManagedService MUST NOT be called back.", calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
if (reg2 != null)
reg2.unregister();
reg2 = null;
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
}
/*
* 9. Test dynamic bindings from getConfiguration(pid) and
* createConfiguration(pid) (Member Bug 2551)
*/
trace("############ 9 testDynamicBinding()");
String dynamicPid1 = Util.createPid("dynamicPid1");
String dynamicPid2 = Util.createPid("dynamicPid2");
String dynamicFactoryPid = Util.createPid("dynamicFactoryPid");
String dynamicFactoryPidInstance = null;
try {
props = new Hashtable();
props.put("StringKey", "String Value");
// make sure this bundle has enough permissions
this.setAppropriatePermission();
// ensure unbound configuration
conf = this.cm.getConfiguration(dynamicPid1, null);
assertNotNull("Configuration must exist for " + dynamicPid1, conf);
assertNull("Configuration must be new for " + dynamicPid1, conf.getProperties());
assertNull("Configuration for " + dynamicPid1 + " must be unbound",
this.getBundleLocationForCompare(conf));
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl("ID1");
reg = getContext().registerService(Synchronizer.class.getName(), sync, propsForSync1);
bundle1 = getContext().installBundle(getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
ServiceReference caref = bundle1.getBundleContext().getServiceReference(ConfigurationAdmin.class);
ConfigurationAdmin ca = (ConfigurationAdmin) bundle1.getBundleContext().getService(caref);
// ensure configuration 1 is bound to bundle1
conf = ca.getConfiguration(dynamicPid1);
assertNotNull("Configuration must exist for " + dynamicPid1, conf);
assertNotNull("Configuration must not be new for " + dynamicPid1, conf.getProperties());
assertEquals("Configuration for " + dynamicPid1 + " must be bound to " + bundle1.getLocation(),
bundle1.getLocation(), this.getBundleLocationForCompare(conf));
// ensure configuration 2 is bound to bundle1
conf = ca.getConfiguration(dynamicPid2);
assertNotNull("Configuration must exist for " + dynamicPid2, conf);
assertNull("Configuration must be new for " + dynamicPid2, conf.getProperties());
assertEquals("Configuration for " + dynamicPid2 + " must be bound to " + bundle1.getLocation(),
bundle1.getLocation(), this.getBundleLocationForCompare(conf));
conf.update(props);
// ensure factory configuration bound to bundle1
conf = ca.createFactoryConfiguration(dynamicFactoryPid);
dynamicFactoryPidInstance = conf.getPid();
assertNotNull("Factory Configuration must exist for " + dynamicFactoryPid, conf);
assertNull("Factory Configuration must be new for " + dynamicFactoryPid, conf.getProperties());
assertEquals(
"Factory Configuration for " + dynamicFactoryPid + " must be bound to " + bundle1.getLocation(),
bundle1.getLocation(), this.getBundleLocationForCompare(conf));
conf.update(props);
SynchronizerImpl sync2 = new SynchronizerImpl("SyncListener");
reg2 = getContext().registerService(ConfigurationListener.class.getName(), new SyncEventListener(sync2),
null);
// unsinstall the bundle, make sure configurations are unbound
this.uninstallBundle(bundle1);
// wait for three (CM_LOCATION_CHANGED) events
boolean threeEvents = sync2.waitForSignal(500, 3);
assertTrue("Expecting three CM_LOCATION_CHANGED events after bundle uninstallation", threeEvents);
// ensure configuration 1 is unbound
conf = this.cm.getConfiguration(dynamicPid1, null);
assertNotNull("Configuration must exist for " + dynamicPid1, conf);
assertNotNull("Configuration must not be new for " + dynamicPid1, conf.getProperties());
assertNull("Configuration for " + dynamicPid1 + " must be unbound", this.getBundleLocationForCompare(conf));
// ensure configuration 2 is unbound
conf = this.cm.getConfiguration(dynamicPid2, null);
assertNotNull("Configuration must exist for " + dynamicPid2, conf);
assertNotNull("Configuration must not be new for " + dynamicPid2, conf.getProperties());
assertNull("Configuration for " + dynamicPid2 + " must be unbound", this.getBundleLocationForCompare(conf));
// ensure factory configuration is unbound
conf = this.cm.getConfiguration(dynamicFactoryPidInstance, null);
assertNotNull("Configuration must exist for " + dynamicFactoryPidInstance, conf);
assertEquals("Configuration " + dynamicFactoryPidInstance + " must be factory configuration for "
+ dynamicFactoryPid, dynamicFactoryPid, conf.getFactoryPid());
assertNotNull("Configuration must not be new for " + dynamicFactoryPidInstance, conf.getProperties());
assertNull("Configuration for " + dynamicFactoryPidInstance + " must be unbound",
this.getBundleLocationForCompare(conf));
} finally {
if (reg != null) reg.unregister();
reg = null;
if (reg2 != null) reg2.unregister();
reg2 = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED) bundle1.uninstall();
bundle1 = null;
conf = cm.getConfiguration(dynamicPid1);
if (conf != null) conf.delete();
conf = cm.getConfiguration(dynamicPid2);
if (conf != null) conf.delete();
if (dynamicFactoryPidInstance != null) {
conf = cm.getConfiguration(dynamicFactoryPidInstance);
if (conf != null) conf.delete();
}
}
}
private void startTargetBundle(Bundle bundle) throws BundleException {
if (this.permissionFlag)
bundle.start();
else {
PermissionInfo[] defPis = permAdmin.getDefaultPermissions();
String[] locations = permAdmin.getLocations();
Map bundlePisMap = null;
if (locations != null) {
bundlePisMap = new HashMap(locations.length);
for (int i = 0; i < locations.length; i++) {
bundlePisMap.put(locations[i],
permAdmin.getPermissions(locations[i]));
}
}
this.resetPermissions();
bundle.start();
// this.printoutPermissions();
this.setPreviousPermissions(defPis, bundlePisMap);
}
}
private void setPreviousPermissions(PermissionInfo[] defPis,
Map bundlePisMap) {
PermissionInfo[] pis = null;
if (bundlePisMap != null)
for (Iterator keys = bundlePisMap.keySet().iterator(); keys
.hasNext();) {
String location = (String) keys.next();
if (location.equals(thisLocation))
pis = (PermissionInfo[]) bundlePisMap.get(location);
else
permAdmin.setPermissions(location,
(PermissionInfo[]) bundlePisMap.get(location));
}
permAdmin.setDefaultPermissions(defPis);
if (pis != null)
permAdmin.setPermissions(thisLocation, pis);
}
private PermissionInfo[] getDefaultPermissionInfos() {
if (permAdmin == null)
return null;
return permAdmin.getDefaultPermissions();
}
private void setInappropriatePermission() throws BundleException {
if (permAdmin == null)
return;
this.resetPermissions();
list.clear();
add(list, PropertyPermission.class.getName(), "*", "READ,WRITE");
add(list, PP, "*", "IMPORT,EXPORTONLY");
add(list, SP, "*", "GET,REGISTER");
// add(list, CP, "*", "CONFIGURE");
add(list, AP, "*", "*");
permissionFlag = false;
this.setBundlePermission(super.getContext().getBundle(), list);
}
private void setAppropriatePermission() throws BundleException {
if (permAdmin == null)
return;
this.resetPermissions();
list.clear();
add(list, PropertyPermission.class.getName(), "*", "READ,WRITE");
add(list, PP, "*", "IMPORT,EXPORTONLY");
add(list, SP, "*", "GET,REGISTER");
add(list, CP, "*", "CONFIGURE");
add(list, AP, "*", "*");
permissionFlag = true;
this.setBundlePermission(super.getContext().getBundle(), list);
}
/**
* TODO comments
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update()
* @spec Configuration.getProperties()
*
* @throws Exception
*/
public void testUpdate() throws Exception {
String pid = Util.createPid();
Configuration conf = cm.getConfiguration(pid);
Dictionary props = conf.getProperties();
assertNull("Properties in conf", props);
Hashtable newprops = new Hashtable();
newprops.put("somekey", "somevalue");
conf.update(newprops);
props = conf.getProperties();
assertNotNull("Properties in conf", props);
assertEquals("conf property 'somekey'", "somevalue",
props.get("somekey"));
Configuration conf2 = cm.getConfiguration(pid);
Dictionary props2 = conf2.getProperties();
assertNotNull("Properties in conf2", props2);
assertEquals("conf2 property 'somekey'", "somevalue",
props2.get("somekey"));
// assertSame("Same configurations", conf, conf2);
// assertEquals("Equal configurations", conf, conf2);
// assertEquals("Equal pids", conf.getPid(), conf2.getPid());
assertTrue("Equal configurations", equals(conf, conf2));
/* check returned properties are copied ones. */
Dictionary props3 = conf2.getProperties();
props3.put("KeyOnly3", "ValueOnly3");
assertTrue("Properties are copied", props2.get("KeyOnly3") == null);
/* Try to update with illegal configuration types */
Hashtable illegalprops = new Hashtable();
Collection v = new ArrayList();
v.add("a string");
v.add(Locale.getDefault());
illegalprops.put("somekey", "somevalue");
illegalprops.put("anotherkey", v);
String message = "updating with illegal properties";
try {
conf2.update(illegalprops);
/* A IllegalArgumentException should have been thrown */
failException(message, IllegalArgumentException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, IllegalArgumentException.class, e);
}
/* contains case variants of the same key name */
props2.put("SomeKey", "SomeValue");
message = "updating with illegal properties (case variants of the same key)";
try {
conf2.update(illegalprops);
/* A IllegalArgumentException should have been thrown */
failException(message, IllegalArgumentException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, IllegalArgumentException.class, e);
}
}
/**
* Tests if we really get the same configuration.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update()
* @spec Configuration.getPid()
* @throws Exception
*/
public void testEquals() throws Exception {
String pid = Util.createPid();
try {
Configuration conf1 = cm.getConfiguration(pid);
Configuration conf2 = cm.getConfiguration(pid);
assertEquals("Equal configurations", conf1, conf2);
assertTrue("Equal configurations", equals(conf1, conf2));
} finally {
cm.getConfiguration(pid).delete();
}
}
/**
* Tests listing of configurations.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec ConfigurationAdmin.listConfigurations(String)
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @throws Exception
*/
public void testListConfigurations() throws Exception {
this.setAppropriatePermission();
/* Create configurations */
/* pid starts with the same prefix */
final String pid11 = Util.createPid("pid11");
final String pid12 = Util.createPid("pid12");
final String pid21 = Util.createPid("pid21");
final String pid22 = Util.createPid("pid22");
final String pid31 = Util.createPid("pid31");
final String pid32 = Util.createPid("pid32");
/* pid does not start with the same prefix */
final String otherPid = "otherPid";
// this.cleanCM();
List configs = new ArrayList(2);
configs.add(cm.getConfiguration(pid11));
configs.add(cm.getConfiguration(pid12));
List updatedConfigs2 = new ArrayList(2);
updatedConfigs2.add(cm.getConfiguration(pid21));
updatedConfigs2.add(cm.getConfiguration(pid22));
Configuration otherConf = cm.getConfiguration(otherPid);
/* location is different */
List updatedConfigs3 = new ArrayList(2);
updatedConfigs3.add(cm.getConfiguration(pid31, neverlandLocation));
updatedConfigs3.add(cm.getConfiguration(pid32, neverlandLocation));
/*
* Update properties on some of configurations (to make them "active")
*/
for (int i = 0; i < updatedConfigs2.size(); i++) {
Hashtable props = new Hashtable();
props.put("someprop" + i, "somevalue" + i);
((Configuration) updatedConfigs2.get(i)).update(props);
}
for (int i = 0; i < updatedConfigs3.size(); i++) {
Hashtable props = new Hashtable();
props.put("someprop" + i, "somevalue" + i);
((Configuration) updatedConfigs3.get(i)).update(props);
}
try {
Configuration[] confs = cm.listConfigurations("(service.pid="
+ Util.createPid() + "*)");
/*
* Returned list must contain all of updateConfigs2 and
* updateConfigs3.
*/
checkIfAllUpdatedConfigs2and3isListed(confs, updatedConfigs2,
updatedConfigs3, null);
/* Inappropriate Permission */
this.setInappropriatePermission();
confs = cm.listConfigurations("(service.pid=" + Util.createPid()
+ "*)");
if (System.getSecurityManager() != null)
/* Returned list must contain all of updateConfigs2. */
checkIfAllUpdatedConfigs2isListed(confs, updatedConfigs2,
updatedConfigs3, null);
else
/*
* Returned list must contain all of updateConfigs2,
* updateConfigs3 and otherConf.
*/
checkIfAllUpdatedConfigs2and3isListed(confs, updatedConfigs2,
updatedConfigs3, otherConf);
/* Appropriate Permission */
this.setAppropriatePermission();
confs = cm.listConfigurations(null);
/*
* Returned list must contain all of updateConfigs2, updateConfigs3
* and otherConf.
*/
checkIfAllUpdatedConfigs2and3isListed(confs, updatedConfigs2,
updatedConfigs3, otherConf);
/* Inappropriate Permission */
this.setInappropriatePermission();
confs = cm.listConfigurations(null);
if (System.getSecurityManager() != null)
/*
* Returned list must contain all of updateConfigs2 and
* otherConf.
*/
checkIfAllUpdatedConfigs2isListed(confs, updatedConfigs2,
updatedConfigs3, otherConf);
else
/*
* Returned list must contain all of updateConfigs2,
* updateConfigs3 and otherConf.
*/
checkIfAllUpdatedConfigs2and3isListed(confs, updatedConfigs2,
updatedConfigs3, otherConf);
/* if the filter string is in valid */
/* must fail because of invalid filter. */
String message = "try to list configurations by invalid filter string.";
try {
cm.listConfigurations("(service.pid=" + Util.createPid() + "*");
/* A InvalidSyntaxException should have been thrown */
failException(message, InvalidSyntaxException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, InvalidSyntaxException.class, e);
}
}
/* Delete all used configurations */
finally {
for (int i = 0; i < configs.size(); i++) {
((Configuration) configs.get(i)).delete();
}
for (int i = 0; i < updatedConfigs2.size(); i++) {
((Configuration) updatedConfigs2.get(i)).delete();
}
for (int i = 0; i < updatedConfigs3.size(); i++) {
((Configuration) updatedConfigs3.get(i)).delete();
}
otherConf.delete();
}
this.setAppropriatePermission();
/* List all configurations and make sure they are all gone */
Configuration[] leftConfs = cm
.listConfigurations("(|(service.pid=" + pid11
+ ")(service.pid=" + pid12 + ")(service.pid=" + pid21
+ ")(service.pid=" + pid22 + ")(service.pid=" + pid31
+ ")(service.pid=" + pid32 + ")(service.pid="
+ otherPid + "))");
assertNull("Left configurations", leftConfs);
}
private void checkIfAllUpdatedConfigs2isListed(Configuration[] confs,
List updatedConfigs2, List updatedConfigs3, Configuration otherConf)
throws IOException, InvalidSyntaxException {
boolean otherFlag = false;
List removedConfigs2 = new ArrayList(updatedConfigs2.size());
confs = cm
.listConfigurations("(service.pid=" + Util.createPid() + "*)");
if (confs == null) {
fail("No configurations returned");
}
for (int i = 0; i < confs.length; i++) {
int index = isPartOf(confs[i], updatedConfigs2);
if (index != -1) {
pass(confs[i].getPid() + " was returned");
removedConfigs2.add(confs[i]);
} else if (otherConf != null && confs[i].equals(otherConf)) {
pass(confs[i].getPid() + " was returned");
otherFlag = true;
} else {
fail(confs[i].getPid() + " should not have been listed");
}
}
if (removedConfigs2.size() != updatedConfigs2.size() || otherFlag) {
fail("All config with nun-null properties and bound to the bundle location cannot be retrieved by listConfigurations().");
}
}
private void checkIfAllUpdatedConfigs2and3isListed(Configuration[] confs,
List updatedConfigs2, List updatedConfigs3, Configuration otherConf)
throws IOException, InvalidSyntaxException {
/*
* List all configurations and make sure that only the active
* configurations are returned
*/
List removedConfigs2 = new ArrayList(updatedConfigs2.size());
List removedConfigs3 = new ArrayList(updatedConfigs3.size());
boolean otherFlag = false;
if (confs == null) {
fail("No configurations returned");
}
for (int i = 0; i < confs.length; i++) {
int index = isPartOf(confs[i], updatedConfigs2);
if (index != -1) {
pass(confs[i].getPid() + " was returned");
removedConfigs2.add(confs[i]);
continue;
}
index = isPartOf(confs[i], updatedConfigs3);
if (index != -1) {
pass(confs[i].getPid() + " was returned");
removedConfigs3.add(confs[i]);
} else if (otherConf != null && equals(confs[i], otherConf)) {
pass(confs[i].getPid() + " was returned");
otherFlag = true;
} else if (!existingConfigs.contains(confs[i].getPid())) {
fail(confs[i].getPid() + " should not have been listed");
}
}
if (removedConfigs2.size() != updatedConfigs2.size()
|| removedConfigs3.size() != updatedConfigs3.size()
|| otherFlag) {
fail("All config with nun-null properties cannot be retrieved by listConfigurations().");
}
}
/**
* Tests to register a ManagedService when a configuration is existing for
* it.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getProperties()
* @spec Configuration.getBundleLocation()
*/
public void testManagedServiceRegistration() throws Exception {
this.setAppropriatePermission();
final String pid = Util.createPid("somepid");
/* create a configuration in advance, then register ManagedService */
Configuration conf = cm.getConfiguration(pid);
trace("created configuration has null properties.");
trace("Create and register a new the ManagedService");
Semaphore semaphore = new Semaphore();
ManagedServiceImpl ms = createManagedService(pid, semaphore);
trace("Wait until the ManagedService has gotten the update");
boolean calledBack = semaphore.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue("ManagedService is called back", calledBack);
trace("Update done!");
conf.delete();
final String pid2 = Util.createPid("somepid2");
Configuration conf2 = cm.getConfiguration(pid2);
Hashtable props = new Hashtable();
props.put("somekey", "somevalue");
props.put("CAPITALkey", "CAPITALvalue");
conf2.update(props);
trace("created configuration has non-null properties.");
trace("Create and register a new the ManagedService");
trace("Wait until the ManagedService has gotten the update");
semaphore = new Semaphore();
ms = createManagedService(pid2, semaphore);
semaphore.waitForSignal();
trace("Update done!");
/*
* Add the two properties added by the CM and then check for equality in
* the properties
*/
props.put(Constants.SERVICE_PID, pid2);
// props.put(SERVICE_BUNDLE_LOCATION, "cm_TBC"); R3 does not include
// service.bundleLocation anymore!
assertEqualProperties("Properties equal?", props, ms.getProperties());
trace((String) ms.getProperties().get("service.pid"));
// trace((String) ms.getProperties().get("service.bundleLocation"));
trace(this.getBundleLocationForCompare(conf2));
/* OUTSIDE_OF_SPEC */
// assertNotSame("Properties same?", props, ms.getProperties());
conf2.delete();
}
private void printoutPropertiesForDebug(SynchronizerImpl sync) {
Dictionary props1 = sync.getProps();
if (props1 == null) {
System.out.println("props = null");
} else {
System.out.println("props = ");
for (Enumeration enums = props1.keys(); enums.hasMoreElements();) {
Object key = enums.nextElement();
System.out.println("\t(" + key + ", " + props1.get(key) + ")");
}
}
}
/**
* Register ManagedService Test 2.
*
* @throws Exception
*/
public void testManagedServiceRegistration2() throws Exception {
this.setAppropriatePermission();
Bundle bundle = getContext().installBundle(
getWebServer() + "targetb1.jar");
final String bundlePid = Util.createPid("bundlePid1");
ServiceRegistration reg = null;
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
trace("###################### A. testManagedServiceRegistration2.");
try {
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService MUST be called back even if no configuration.",
calledback);
assertNull("called back with null props", sync.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(bundlePid,
bundle.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
assertFalse("ManagedService must NOT be called back", calledback);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-A");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", getName() + "-A", props.get("StringKey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 2", 2, props.size());
/* stop and restart target bundle */
bundle.stop();
bundle.start();
trace("The target bundle has been started. Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
// printoutPropertiesForDebug(sync);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNull("called back with null props", sync.getProps());
Configuration[] confs = cm.listConfigurations(null);
assertTrue("confs must be empty:", confs == null
|| (existingConfigs.size() > 0 && confs.length == existingConfigs.size()));
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
/*
* B1. (1)Register ManagedService in advance. (2)create Configuration
* with different location and null props (3)setBundleLocation to the
* target bundle.
*/
trace("###################### B1. testManagedServiceRegistration2.");
try {
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService must be called back even if no configuration.",
calledback);
assertNull("called back with null props", sync.getProps());
trace("The configuration with different location is being created ");
Configuration conf = cm.getConfiguration(bundlePid,
neverlandLocation);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
this.printoutPropertiesForDebug(sync);
assertFalse("ManagedService must NOT be called back", calledback);
/* The conf has null props. */
trace("The configuration is being set to the target bundle");
conf.setBundleLocation(bundle.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
/*
* The spec seems unclear whether the ManagedService registered by
* the newly bound bundle should be called back with null or not
* called back. The implementator of this CT (Ikuo) thinks CT should
* accept either case of (a) No callback. (b) callback with null.
* Otherwise, it fails. Spec of version 1.3
*/
if (calledback) {
count++;
assertNull(
"The props called back MUST be null, if the ManagedService is called back.",
sync.getProps());
}
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B1");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", getName() + "-B1", props.get("StringKey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 2", 2, props.size());
trace("The configuration is being updated to null.");
/* props is reset */
conf.update(new Hashtable(0));
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("Size of props must be 1", 1, props.size());
conf.update(props);
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
trace("The configuration is being set to different location");
conf.setBundleLocation(neverlandLocation);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNull("called back with null props", sync.getProps());
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertFalse("ManagedService must Not be called back", calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
/*
* B2. (1)create Configuration with different location and non-null
* props. (2) Register ManagedService. (3)setBundleLocation to the
* target bundle.
*/
trace("###################### B2. testManagedServiceRegistration2.");
try {
trace("The configuration with different location is being created ");
Configuration conf = cm.getConfiguration(bundlePid,
neverlandLocation);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B2");
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
//assertFalse(
// "ManagedService must NOT be called back even if no configuration.",
// calledback);
assertTrue(
"ManagedService MUST be called back with null parameter when there is no configuration.",
calledback);
trace("The configuration is being updated ");
props.put("StringKey", "stringvalue2");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
this.printoutPropertiesForDebug(sync);
assertFalse("ManagedService must NOT be called back", calledback);
/* The conf has non-null props. */
trace("The configuration is being set to the target bundle");
conf.setBundleLocation(bundle.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
/*
* XXX Felix and Ikuo think the ManagedService registered by the
* newly bound bundle should be called back with the props. However,
* BJ thinks no. The implementator of this CT (Ikuo) thinks CT
* should not check it because it is unclear in the spec of version
* 1.3.
*/
// assertTrue("ManagedService must be called back", calledback);
// assertFalse("ManagedService must NOT be called back",
// calledback);
if (calledback) {
++count;
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", "stringvalue2", props.get("StringKey"));
assertEquals("Size of props must be 2", 2, props.size());
}
trace("The configuration is being updated ");
props.put("StringKey", "stringvalue3");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", "stringvalue3", props.get("StringKey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 2", 2, props.size());
trace("The configuration is being set to different location");
conf.setBundleLocation(neverlandLocation);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
/*
* XXX Felix and Ikuo think the ManagedService registered by the
* newly bound bundle should be called back with null. However, BJ
* thinks no. The implementator of this CT (Ikuo) thinks CT should
* not check it strictly because it is unclear in the spec of
* version 1.3.
*/
// assertTrue("ManagedService must be called back", calledback);
if (calledback) {
++count;
assertNull("called back with null props", sync.getProps());
}
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertFalse("ManagedService must Not be called back", calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
/*
* B3. (1)create Configuration with different location and null props.
* (2) Register ManagedService. (3)setBundleLocation to the target
* bundle.
*/
trace("###################### B3. testManagedServiceRegistration2.");
try {
trace("The configuration with different location is being created ");
Configuration conf = cm.getConfiguration(bundlePid,
neverlandLocation);
trace("The configuration is being updated ");
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
//assertFalse(
// "ManagedService must NOT be called back even if no configuration.",
// calledback);
assertTrue(
"ManagedService MUST be called back with null parameter when there is no configuration.",
calledback);
assertNull("called back with null props", sync.getProps());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B3");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
this.printoutPropertiesForDebug(sync);
assertFalse("ManagedService must NOT be called back", calledback);
/* The conf has non-null props. */
trace("The configuration is being set to the target bundle");
conf.setBundleLocation(bundle.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", getName() + "-B3", props.get("StringKey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 2", 2, props.size());
trace("The configuration is being set to different location");
conf.setBundleLocation(neverlandLocation);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
/*
* XXX Felix and Ikuo think the ManagedService registered by the
* newly bound bundle should be called back with null. However, BJ
* thinks no. The implementator of this CT (Ikuo) thinks CT should
* not check it strictly because it is unclear in the spec of
* version 1.3.
*/
// assertTrue("ManagedService must be called back", calledback);
if (calledback) {
++count;
assertNull("called back with null props", sync.getProps());
}
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertFalse("ManagedService must NOT be called back", calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
/*
* C. Configuration Admin Service is stopped once. After a while, it
* restarts.
*
* 1.Register ManagedService in advance. 2.create Configuration with
* different location. 3.setBundleLocation to the target bundle.
*/
Bundle cmBundle = stopCmBundle();
try {
int count = 0;
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
/* restart where no configuration. */
trace("Wait for restart cm bundle.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService is Called back even if no configuration.",
calledback);
this.cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
/* Create configuration and stop/start cm. */
Configuration conf = cm.getConfiguration(bundlePid,
bundle.getLocation());
cmBundle = stopCmBundle();
trace("Wait for restart cm bundle.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService is Called back.", calledback);
this.cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
//conf.delete();
cm.getConfiguration(bundlePid).delete();
/* Create configuration with null location and stop/start cm. */
conf = cm.getConfiguration(bundlePid, null);
cmBundle = stopCmBundle();
trace("Wait for restart cm bundle.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue(
"ManagedService is Called back even if configuration with null.",
calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
}
/**
* Register ManagedService in advance. ManagedService has multiple pids.
* Then create Configuration.
*
* @throws Exception
*/
public void testManagedServiceRegistrationWithMultiplPIDs()
throws Exception {
this.setAppropriatePermission();
try {
trace("########## 1(array) testManagedServiceRegistrationWithMultiplPIDs");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_MODE,
org.osgi.test.cases.cm.shared.Constants.MODE_ARRAY);
internalTestRegisterManagedServiceWithMultiplePIDs();
trace("########## 1(list) testManagedServiceRegistrationWithMultiplPIDs");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_MODE,
org.osgi.test.cases.cm.shared.Constants.MODE_LIST);
internalTestRegisterManagedServiceWithMultiplePIDs();
trace("########## 1(set) testManagedServiceRegistrationWithMultiplPIDs");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_MODE,
org.osgi.test.cases.cm.shared.Constants.MODE_SET);
internalTestRegisterManagedServiceWithMultiplePIDs();
} finally {
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_MODE,
org.osgi.test.cases.cm.shared.Constants.MODE_UNARY);
}
}
private void internalTestRegisterManagedServiceWithMultiplePIDs()
throws BundleException, IOException {
final String bundlePid1 = Util.createPid("bundlePid1");
final String bundlePid2 = Util.createPid("bundlePid2");
ServiceRegistration reg = null;
Bundle bundle1 = null;
try {
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
SynchronizerImpl sync = new SynchronizerImpl();
trace("1 sync.getCount()=" + sync.getCount());
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService MUST be called back even if no configuration.",
calledback);
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
if (!calledback)
--count;
trace("sync.getCount()=" + sync.getCount());
trace("The configuration1 is being created");
trace("sync.getCount()=" + sync.getCount());
Configuration conf1 = cm.getConfiguration(bundlePid1,
bundle1.getLocation());
trace("sync.getCount()=" + sync.getCount());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
assertFalse("ManagedService must NOT be called back", calledback);
trace("The configuration2 is being created");
Configuration conf2 = cm.getConfiguration(bundlePid2,
bundle1.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
trace("sync.getCount()=" + sync.getCount());
assertFalse("ManagedService must NOT be called back", calledback);
trace("The configuration1 is being updated ");
Dictionary props1 = new Hashtable();
props1.put("StringKey1", "stringvalue1");
conf1.update(props1);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
trace("sync.getCount()=" + sync.getCount());
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
Dictionary props = sync.getProps();
assertEquals("pid", bundlePid1, props.get(Constants.SERVICE_PID));
assertEquals("pid", "stringvalue1", props.get("StringKey1"));
trace("The configuration2 is being updated ");
Dictionary props2 = new Hashtable();
props2.put("StringKey1", "stringvalue1");
props2.put("StringKey2", "stringvalue2");
conf2.update(props2);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid2, props.get(Constants.SERVICE_PID));
assertEquals("pid", "stringvalue1", props.get("StringKey1"));
assertEquals("pid", "stringvalue2", props.get("StringKey2"));
assertEquals("Size of props must be 3", 3, props.size());
trace("The configuration1 is being deleted ");
conf1.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
trace("The configuration2 is being deleted ");
conf2.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
}
}
/**
* Register ManagedService in advance. Then create Configuration.
*
* @throws Exception
*/
public void testManagedServiceRegistrationDuplicatedTargets()
throws Exception {
this.setAppropriatePermission();
Bundle bundle2 = getContext().installBundle(
getWebServer() + "targetb2.jar");
final String bundlePid = Util.createPid("bundlePid1");
ServiceRegistration reg2 = null;
/*
* A. One bundle registers duplicated ManagedService. Both of them must
* be called back.
*/
trace("################## A testManagedServiceRegistrationDuplicatedTargets()");
try {
SynchronizerImpl sync2 = new SynchronizerImpl();
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_DUPCOUNT,
"2");
this.startTargetBundle(bundle2);
trace("Wait for signal.");
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertTrue(
"Both ManagedService MUST be called back even if no configuration.",
calledback2);
assertNull("called back with null props", sync2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(bundlePid,
bundle2.getLocation());
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 3);
assertFalse("ManagedService must NOT be called back", calledback2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-A");
conf.update(props);
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 4);
assertTrue("Both ManagedService must be called back", calledback2);
/* stop and restart target bundle */
bundle2.stop();
bundle2.start();
trace("The target bundle has been stopped and re-started. Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 6);
assertTrue("Both ManagedService must be called back", calledback2);
// printoutPropertiesForDebug(sync);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 8);
assertTrue("Both ManagedService must be called back", calledback2);
assertNull("null props must be called back", sync2.getProps());
} finally {
if (reg2 != null)
reg2.unregister();
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
}
/*
* B1. (1)No Configuration. (2)two bundles register duplicated
* ManagedService. ==> Only one, firstly registered, must be called
* back.
*/
trace("################## B1 testManagedServiceRegistrationDuplicatedTargets()");
reg2 = null;
ServiceRegistration reg1 = null;
Bundle bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_DUPCOUNT,
"1");
bundle2 = getContext().installBundle(getWebServer() + "targetb2.jar");
try {
SynchronizerImpl sync2 = new SynchronizerImpl("ID2");
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
this.startTargetBundle(bundle2);
trace("Wait for signal.");
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 1);
assertTrue(
"ManagedService MUST be called back even if no configuration.",
calledback2);
assertNull("null props must be called back", sync2.getProps());
SynchronizerImpl sync1 = new SynchronizerImpl("ID1");
reg1 = getContext().registerService(Synchronizer.class.getName(),
sync1, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, 1);
assertTrue(
"ManagedService MUST be called back even if no configuration.",
calledback1);
trace("The configuration is being created");
Configuration[] confs = cm.listConfigurations(null);
assertTrue("confs must be empty:", confs == null
|| (existingConfigs.size() > 0 && confs.length == existingConfigs.size()));
Configuration conf = cm.getConfiguration(bundlePid,
bundle2.getLocation());
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 2);
this.printoutPropertiesForDebug(sync2);
assertFalse("ManagedService must NOT be called back", calledback2);
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertFalse("ManagedService must NOT be called back", calledback1);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B1");
conf.update(props);
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertFalse("ManagedService must NOT be called back", calledback1);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 3);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
assertNull("null props must be called back", sync2.getProps());
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertFalse("ManagedService must NOT be called back", calledback1);
} finally {
if (reg1 != null)
reg1.unregister();
reg1 = null;
if (reg2 != null)
reg2.unregister();
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
}
/*
* B2. (1) Create new Conf with null props. (2)two bundles register
* duplicated ManagedService. ==> Only one, firstly registered, must be
* called back.
*/
trace("################## B2 testManagedServiceRegistrationDuplicatedTargets()");
reg2 = null;
reg1 = null;
bundle1 = getContext().installBundle(getWebServer() + "targetb1.jar");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_DUPCOUNT,
"1");
bundle2 = getContext().installBundle(getWebServer() + "targetb2.jar");
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(bundlePid,
bundle2.getLocation());
SynchronizerImpl sync2 = new SynchronizerImpl("ID2");
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
this.startTargetBundle(bundle2);
trace("Wait for signal.");
int count2 = 0;
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME,
++count2);
assertTrue(
"ManagedService MUST be called back even if configuration has no props.",
calledback2);
assertNull("null props must be called back", sync2.getProps());
SynchronizerImpl sync1 = new SynchronizerImpl("ID1");
reg1 = getContext().registerService(Synchronizer.class.getName(),
sync1, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
int count1 = 0;
boolean calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME,
++count1);
//assertFalse("ManagedService MUST NOT be called back even.",
// calledback1);
assertTrue(
"ManagedService MUST be called back even if deffirent bound location.",
calledback1);
assertNull("null props must be called back", sync1.getProps());
Configuration[] confs = cm.listConfigurations(null);
assertTrue("confs must be empty:", confs == null
|| (existingConfigs.size() > 0 && confs.length == existingConfigs.size()));
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B2");
conf.update(props);
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, count1 + 1);
assertFalse("ManagedService must NOT be called back", calledback1);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
assertNull("null props must be called back", sync2.getProps());
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, count1 + 1);
assertFalse("ManagedService must NOT be called back", calledback1);
} finally {
if (reg1 != null)
reg1.unregister();
reg1 = null;
if (reg2 != null)
reg2.unregister();
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
}
/*
* B3. (1) Create new Conf with non-null props. (2)two bundles register
* duplicated ManagedService. ==> Only one, firstly registered, must be
* called back.
*/
trace("################## B3 testManagedServiceRegistrationDuplicatedTargets()");
reg2 = null;
reg1 = null;
bundle1 = getContext().installBundle(getWebServer() + "targetb1.jar");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_DUPCOUNT,
"1");
bundle2 = getContext().installBundle(getWebServer() + "targetb2.jar");
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(bundlePid,
bundle2.getLocation());
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B3");
conf.update(props);
SynchronizerImpl sync2 = new SynchronizerImpl("ID2");
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
this.startTargetBundle(bundle2);
trace("Wait for signal.");
int count2 = 0;
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME,
++count2);
assertTrue("ManagedService MUST be called back.", calledback2);
assertNotNull("called back with null props", sync2.getProps());
SynchronizerImpl sync1 = new SynchronizerImpl("ID1");
reg1 = getContext().registerService(Synchronizer.class.getName(),
sync1, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
int count1 = 0;
boolean calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME,
++count1);
//assertFalse("ManagedService MUST NOT be called back.", calledback1);
assertTrue(
"ManagedService MUST be called back even if deffirent bound location.",
calledback1);
assertNull("null props must be called back", sync1.getProps());
Configuration[] confs = cm.listConfigurations(null);
assertNotNull("confs must NOT be empty:", confs);
trace("The configuration is being updated ");
props.put("StringKey2", "stringvalue2");
conf.update(props);
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, count1 + 1);
assertFalse("ManagedService must NOT be called back", calledback1);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
assertNull("null props must be called back", sync2.getProps());
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, count1 + 1);
assertFalse("ManagedService must NOT be called back", calledback1);
} finally {
if (reg1 != null)
reg1.unregister();
reg1 = null;
if (reg2 != null)
reg2.unregister();
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
}
}
private Bundle stopCmBundle() {
ServiceReference reference = this.getContext().getServiceReference(ConfigurationAdmin.class.getName());
Bundle cmBundle = reference.getBundle();
try {
cmBundle.stop();
} catch (BundleException be) {
fail("Error stopping CM Bundle: " + be);
}
cm = null;
return cmBundle;
}
private void assignCm() {
cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
}
private void startCmBundle(Bundle cmBundle) {
try {
cmBundle.start();
} catch (BundleException be) {
fail("Error starting CM Bundle: " + be);
}
assignCm();
}
private Dictionary getManagedProperties(String pid) throws Exception {
Semaphore semaphore = new Semaphore();
ManagedServiceImpl ms = createManagedService(pid, semaphore);
semaphore.waitForSignal();
return ms.getProperties();
}
/**
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getProperties()
* @throws Exception
*/
public void testManagedProperties() throws Exception {
String pid = Util.createPid("somepid");
/* Set up the configuration */
Configuration conf = cm.getConfiguration(pid);
/* Put all legal types in the properties and update */
Hashtable props = new Hashtable();
props.put("StringKey", getName());
props.put("IntegerKey", new Integer(12));
props.put("LongKey", new Long(-29));
props.put("FloatKey", new Float(921.14));
props.put("DoubleKey", new Double(1827.234));
props.put("ByteKey", new Byte((byte) 127));
props.put("ShortKey", new Short((short) 1));
// props.put("BigIntegerKey", new BigInteger("123"));
// props.put("BigDecimalkey", new BigDecimal(9872.7643));
props.put("CharacterKey", new Character('N'));
props.put("BooleanKey", new Boolean(true));
Collection v = new ArrayList();
v.add(getName());
// ### is now invalid ....
// v.addElement(new Integer(12));
// v.addElement(new Long(-29));
// v.addElement(new Float(921.14));
// v.addElement(new Double(1827.234));
// v.addElement(new Byte((byte) 127));
// v.addElement(new Short((short) 1));
// v.addElement(new BigInteger("123"));
// v.addElement(new BigDecimal(9872.7643));
// v.addElement(new Character('N'));
// v.addElement(new Boolean(true));
// v.addElement(new String[] {"firststring", "secondstring"});
// ### end invalid
props.put("collectionkey", v);
props.put("StringArray", new String[] { "string1", "string2" });
props.put("IntegerArray", new Integer[] { new Integer(1),
new Integer(2) });
props.put("LongArray", new Long[] { new Long(1), new Long(2) });
props.put("FloatArray", new Float[] { new Float(1.1), new Float(2.2) });
props.put("DoubleArray", new Double[] { new Double(1.1),
new Double(2.2) });
props.put("ByteArray", new Byte[] { new Byte((byte) -1),
new Byte((byte) -2) });
props.put("ShortArray", new Short[] { new Short((short) 1),
new Short((short) 2) });
// props.put("BigIntegerArray", new BigInteger[] {
// new BigInteger("1"), new BigInteger("2")
// }
//
// );
// props.put("BigDecimalArray", new BigDecimal[] {
// new BigDecimal(1.1), new BigDecimal(2.2)
// }
//
// );
props.put("CharacterArray", new Character[] { new Character('N'),
new Character('O') });
props.put("BooleanArray", new Boolean[] { new Boolean(true),
new Boolean(false) });
// ### invalid
// Vector v1 = new Vector();
// v1.addElement(new Vector());
// v1.addElement("Anystring");
// props.put("VectorArray", new Vector[] {v1, new Vector()});
props.put("CAPITALkey", "CAPITALvalue");
conf.update(props);
/* Register a managed service and get the properties */
Dictionary msprops = getManagedProperties(pid);
/*
* Add the two properties added by the CM and then check for equality in
* the properties (including preserved case)
*/
props.put(Constants.SERVICE_PID, pid);
// props.put(SERVICE_BUNDLE_LOCATION, "cm_TBC"); R3 does not include
// service.bundleLocation anymore!
assertEqualProperties("Properties equal?", props, msprops);
/* Check if the properties are case independent */
String s = (String) msprops.get("sTringkeY");
assertEquals("case independant properties", getName(), s);
Hashtable illegalprops = new Hashtable();
illegalprops.put("exception", new Exception());
String message = "Exception is not a legal type";
try {
conf.update(illegalprops);
/* A IllegalArgumentException should have been thrown */
failException(message, IllegalArgumentException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, IllegalArgumentException.class, e);
}
/* TODO: Add more illegal types (inside collections etc) */
}
// public void testUpdatedProperties() throws Exception {
// /* Put all legal types in the properties and update */
// /* Get the properties again */
// /* Check if the properties are equals */
// /* Check if the properties have preserved the case */
// /* Check if the properties are case independent */
// }
/**
* Test created Factory configuration without location.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getProperties()
* @spec Configuration.getBundleLocation()
* @throws Exception
*/
public void testCreateFactoryConfiguration() throws Exception {
commonTestCreateFactoryConfiguration(false, getLocation());
}
/**
* Test created Factory configuration with location.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String,String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getProperties()
* @spec Configuration.getBundleLocation()
* @throws Exception
*/
public void testCreateFactoryConfigurationWithLocation() throws Exception {
commonTestCreateFactoryConfiguration(true, neverlandLocation);
}
/**
* Test created Factory configuration with null location.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String,String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getProperties()
* @spec Configuration.getBundleLocation()
* @throws Exception
*/
public void testCreateFactoryConfigurationWithNullLocation()
throws Exception {
commonTestCreateFactoryConfiguration(true, null);
}
private void commonTestCreateFactoryConfiguration(boolean withLocation,
String location) throws Exception {
final int NUMBER_OF_CONFIGS = 3;
final String factorypid = Util.createPid("somefactorypid");
final List pids = new ArrayList();
final List configs = new ArrayList();
// Inappropriate Permission
this.setInappropriatePermission();
pids.add(factorypid);
for (int i = 0; i < NUMBER_OF_CONFIGS; i++) {
Configuration conf = null;
if (withLocation) {
/*
* Without appropriate ConfigurationPermission, create
* FactoryConfiguration with specfied location.
*/
String message = "try to create factory configuration without appropriate ConfigurationPermission.";
try {
conf = cm.createFactoryConfiguration(factorypid, location);
/*
* A SecurityException should have been thrown if security
* is enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if
* security is not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
continue;
} else {
/*
* Even appropriate ConfigurationPermission,
* createFactoryConfiguration(factorypid) must be succeed
*/
conf = cm.createFactoryConfiguration(factorypid);
}
configs.add(conf);
trace("pid: " + conf.getPid());
assertTrue("Unique pid", !pids.contains(conf.getPid()));
assertEquals("Correct factory pid", factorypid,
conf.getFactoryPid());
assertNull("No properties", conf.getProperties());
assertEquals("Correct location", location,
getBundleLocationForCompare(conf));
/* Add the pid to the list */
pids.add(conf.getPid());
}
for (int i = 0; i < configs.size(); i++) {
Configuration conf = (Configuration) configs.get(i);
conf.delete();
}
// Appropriate Permission
pids.clear();
configs.clear();
this.setAppropriatePermission();
pids.add(factorypid);
for (int i = 0; i < NUMBER_OF_CONFIGS; i++) {
Configuration conf = null;
if (withLocation) {
conf = cm.createFactoryConfiguration(factorypid, location);
} else {
conf = cm.createFactoryConfiguration(factorypid);
}
configs.add(conf);
trace("pid: " + conf.getPid());
assertTrue("Unique pid", !pids.contains(conf.getPid()));
assertEquals("Correct factory pid", factorypid,
conf.getFactoryPid());
assertNull("No properties", conf.getProperties());
assertEquals("Correct location", location,
this.getBundleLocationForCompare(conf));
/* Add the pid to the list */
pids.add(conf.getPid());
}
for (int i = 0; i < configs.size(); i++) {
Configuration conf = (Configuration) configs.get(i);
conf.delete();
}
}
private String getBundleLocationForCompare(Configuration conf)
throws BundleException {
String location = null;
if (this.permissionFlag) {
try {
location = conf.getBundleLocation();
} catch (SecurityException se) {
// Bug 2539: Need to be hard on granting appropriate permission
System.out.println("Temporarily grant CONFIGURE(" + thisLocation
+ ") to get location of configuration " + conf.getPid());
List perms = getBundlePermission(thisBundle);
try {
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
location = conf.getBundleLocation();
} catch (SecurityException se2) {
throw se;
} finally {
System.out.println("Resetting permissions for " + thisLocation + " to: " + perms);
resetBundlePermission(thisBundle, perms);
}
}
} else {
this.setAppropriatePermission();
location = conf.getBundleLocation();
this.setInappropriatePermission();
}
return location;
}
public void testFactoryConfigurationCollision() throws IOException, InvalidSyntaxException, BundleException {
final String factoryPid = Util.createPid("factoryPid1");
final Configuration cf = cm.createFactoryConfiguration( factoryPid, null );
assertNotNull( cf );
final String pid = cf.getPid();
List list = new ArrayList(3);
Bundle bundle = getContext().installBundle(getWebServer() + "bundleT1.jar");
try
{
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(), sync1_1, propsForSyncF1_1));
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count1_1 = 0;
assertNoCallback(sync1_1, count1_1);
assertNotNull( "Configuration must have PID", pid );
assertEquals( "Factory configuration must have requested factory PID", factoryPid, cf.getFactoryPid() );
// assert getConfiguration returns the same configurtion
final Configuration c1 = cm.getConfiguration( pid, null );
assertEquals( "getConfiguration must retrieve required PID", pid, c1.getPid() );
assertEquals( "getConfiguration must retrieve new factory configuration", factoryPid, c1.getFactoryPid() );
assertNull( "Configuration must not have properties", c1.getProperties() );
assertNoCallback(sync1_1, count1_1);
// restart config admin and verify getConfiguration persisted
// the new factory configuration as such
restartCM();
assertNotNull( "Config Admin Service missing", cm );
assertNoCallback(sync1_1, count1_1);
final Configuration c2 = cm.getConfiguration( pid, null );
assertEquals( "getConfiguration must retrieve required PID", pid, c2.getPid() );
assertEquals( "getConfiguration must retrieve new factory configuration from persistence", factoryPid, c2.getFactoryPid() );
assertNull( "Configuration must not have properties", c2.getProperties() );
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
c2.update( props );
count1_1 = assertCallback(sync1_1, count1_1);
props = sync1_1.getProps();
assertEquals( "stringvalue", props.get( "StringKey" ) );
final Configuration[] cfs = cm.listConfigurations( "(" + ConfigurationAdmin.SERVICE_FACTORYPID + "="
+ factoryPid + ")" );
assertNotNull( "Expect at least one configuration", cfs );
assertEquals( "Expect exactly one configuration", 1, cfs.length );
assertEquals( cf.getPid(), cfs[0].getPid() );
assertEquals( cf.getFactoryPid(), cfs[0].getFactoryPid() );
}
finally
{
// make sure no configuration survives ...
this.cleanUpForCallbackTest(bundle, null, null, list);
cm.getConfiguration( pid, null ).delete();
}
}
/**
* Test Managed Service Factory.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getProperties()
* @spec ManagedServiceFactory.updated(String,Dictionary)
* @throws Exception
*/
public void testManagedServiceFactory() throws Exception {
final int NUMBER_OF_CONFIGS = 3;
String factorypid = Util.createPid("somefactorypid");
Hashtable configs = new Hashtable();
/* Create some factory configurations */
for (int i = 0; i < NUMBER_OF_CONFIGS; i++) {
Configuration conf = cm.createFactoryConfiguration(factorypid);
Hashtable ht = new Hashtable();
ht.put("test.field", i + "");
conf.update(ht);
trace("pid: " + conf.getPid());
configs.put(conf.getPid(), conf);
}
try {
Semaphore semaphore = new Semaphore();
/* Register a factory */
ManagedServiceFactoryImpl msf = new ManagedServiceFactoryImpl(
"msf", "testprop", semaphore);
Hashtable properties = new Hashtable();
properties.put(Constants.SERVICE_PID, factorypid);
properties.put(ConfigurationAdmin.SERVICE_FACTORYPID, factorypid);
registerService(ManagedServiceFactory.class.getName(), msf,
properties);
for (int i = 0; i < NUMBER_OF_CONFIGS; i++) {
trace("Wait for signal #" + i);
semaphore.waitForSignal();
trace("Signal #" + i + " arrived");
}
trace("All signals have arrived");
} finally {
Enumeration keys = configs.keys();
while (keys.hasMoreElements()) {
Configuration conf = (Configuration) configs.get(keys
.nextElement());
conf.delete();
}
}
}
/**
* Tests a configuration listener update event notification from a
* configuration service. The event data should match the data that
* originated the event (pid, factorypid...).
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @spec Configuration.update(Dictionary)
* @throws Exception
*/
public void testUpdateConfigEvent() throws Exception {
ConfigurationListenerImpl cl = null;
String pid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
SynchronizerImpl synchronizer = new SynchronizerImpl();
/* Set up the configuration */
Configuration conf = cm.getConfiguration(pid);
Hashtable props = new Hashtable();
props.put("key", "value1");
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
try {
conf.update(props);
trace("Wait until the ConfigurationListener has gotten the update");
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType());
assertNull("Config Factory event pid null", cl.getFactoryPid());
assertNotNull("Config event reference null", cl.getReference());
ConfigurationAdmin admin = (ConfigurationAdmin) getContext()
.getService(cl.getReference());
try {
assertNotNull("Configuration Admin from event", admin);
Configuration config = admin.getConfiguration(cl.getPid());
assertNotNull("Configuration from event", config);
assertEqualProperties("Properties match", conf.getProperties(),
config.getProperties());
} finally {
getContext().ungetService(cl.getReference());
}
} finally {
removeConfigurationListener(cl);
}
}
/**
* Tests a configuration listener update event notification from a
* configuration service factory. The event data should match the data that
* originated the event (pid, factorypid...).
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.getPid()
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testUpdateConfigFactoryEvent() throws Exception {
ConfigurationListenerImpl cl = null;
String factorypid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
SynchronizerImpl synchronizer = new SynchronizerImpl();
/* Set up the configuration */
Configuration conf = cm.createFactoryConfiguration(factorypid);
String pid = conf.getPid();
Hashtable props = new Hashtable();
props.put("key", "value1");
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
conf.update(props);
trace("Wait until the ConfigurationListener has gotten"
+ "the config factory update");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType());
assertEquals("Config Factory event pid match", factorypid,
cl.getFactoryPid());
assertNotNull("Config Factory event reference null",
cl.getReference());
ConfigurationAdmin admin = (ConfigurationAdmin) getContext()
.getService(cl.getReference());
try {
assertNotNull("Configuration Admin from event", admin);
Configuration config = admin.getConfiguration(cl.getPid());
assertNotNull("Configuration from event", config);
assertEqualProperties("Properties match", conf.getProperties(),
config.getProperties());
} finally {
getContext().ungetService(cl.getReference());
}
} finally {
removeConfigurationListener(cl);
}
}
/**
* Tests a configuration listener delete event notification from a
* configuration service. The deleted <code>Configuration</code> should be
* empty (<code>ConfigurationAdmin.listConfigurations(null)</code> must not
* contain the deleted <code>Configuration</code>).
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @spec ConfigurationAdmin.listConfigurations(String)
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testDeleteConfigEvent() throws Exception {
ConfigurationListenerImpl cl = null;
String pid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
SynchronizerImpl synchronizer = new SynchronizerImpl();
/* Set up the configuration */
Configuration conf = cm.getConfiguration(pid);
Hashtable props = new Hashtable();
props.put("key", "value1");
trace("Create and register a new ConfigurationListener");
try {
cl = createConfigurationListener(synchronizer, 2);
conf.update(props);
trace("Wait until the ConfigurationListener has gotten the update");
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
conf.delete();
trace("Wait until the ConfigurationListener has gotten the delete");
assertTrue("Delete done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME, 2));
assertEquals("Config event pid match", pid, cl.getPid(2));
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, cl.getType(2));
assertNull("Config Factory event pid null", cl.getFactoryPid(2));
assertNotNull("Config Factory event reference null",
cl.getReference(2));
try {
ConfigurationAdmin admin = (ConfigurationAdmin) getContext()
.getService(cl.getReference(2));
assertNotNull("Configuration Admin from event", admin);
Configuration[] configs = admin
.listConfigurations("(service.pid=" + pid + ")");
assertNull("The configuration exists in CM!", configs);
} finally {
getContext().ungetService(cl.getReference(2));
}
} finally {
removeConfigurationListener(cl);
}
}
/**
* Tests a configuration listener delete event notification from a
* configuration service factory. The deleted <code>Configuration</code>
* should be empty (
* <code>ConfigurationAdmin.listConfigurations(null)</code> must not contain
* the deleted <code>Configuration</code>).
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @spec ConfigurationAdmin.listConfigurations(String)
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testDeleteConfigFactoryEvent() throws Exception {
ConfigurationListenerImpl cl = null;
String factorypid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
SynchronizerImpl synchronizer = new SynchronizerImpl();
/* Set up the configuration */
Configuration conf = cm.createFactoryConfiguration(factorypid);
String pid = conf.getPid();
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
conf.delete();
trace("Wait until the ConfigurationListener has gotten"
+ "the config factory delete");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, cl.getType());
assertEquals("Config Factory event pid match", factorypid,
cl.getFactoryPid());
assertNotNull("Config Factory event reference null",
cl.getReference());
ConfigurationAdmin admin = (ConfigurationAdmin) getContext()
.getService(cl.getReference());
try {
assertNotNull("Configuration Admin from event", admin);
Configuration[] configs = admin
.listConfigurations("(service.factoryPid=" + factorypid
+ ")");
assertNull("The configuration exists in CM!", configs);
} finally {
getContext().ungetService(cl.getReference());
}
} finally {
removeConfigurationListener(cl);
}
}
/**
* Tests a configuration listener permission. The bundle does not have
* <code>ServicePermission[ConfigurationListener,REGISTER]</code> and will
* try to register a <code>ConfigurationListener</code>. An exception must
* be thrown.
*
* @spec BundleContext.installBundle(String)
* @spec Bundle.start()
*
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testConfigListenerPermission() throws Exception {
Bundle tb = getContext().installBundle(getWebServer() + "tb1.jar");
String message = "registering config listener without permission";
try {
tb.start();
/* A BundleException should have been thrown if security is enabled */
if (System.getSecurityManager() != null)
failException(message, BundleException.class);
} catch (BundleException e) {
/* Check that we got the correct exception */
assertException(message, BundleException.class, e);
/*
* A BundleException should not have been thrown if security is not
* enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
} finally {
tb.uninstall();
}
}
/**
* Tests an event from a different bundle. The
* <code>ConfigurationListener</code> should get the event even if it was
* generated from a different bundle.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testConfigEventFromDifferentBundle() throws Exception {
trace("Create and register a new ConfigurationListener");
SynchronizerImpl synchronizer = new SynchronizerImpl();
ConfigurationListenerImpl cl = createConfigurationListener(
synchronizer, 4);
Bundle tb = getContext().installBundle(getWebServer() + "tb2.jar");
tb.start();
trace("Wait until the ConfigurationListener has gotten the update");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertEquals("Config event pid match", PACKAGE + ".tb2pid."
+ ConfigurationListenerImpl.LISTENER_PID_SUFFIX,
cl.getPid(1));
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType(1));
assertNull("Config Factory event pid null", cl.getFactoryPid(1));
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME, 2));
assertEquals("Config event pid match", PACKAGE + ".tb2pid."
+ ConfigurationListenerImpl.LISTENER_PID_SUFFIX,
cl.getPid(2));
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, cl.getType(2));
assertNull("Config Factory event pid null", cl.getFactoryPid(2));
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME, 3));
assertEquals("Config event facotory pid match", PACKAGE
+ ".tb2factorypid."
+ ConfigurationListenerImpl.LISTENER_PID_SUFFIX,
cl.getFactoryPid(3));
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType(3));
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME, 4));
assertEquals("Config event factory pid match", PACKAGE
+ ".tb2factorypid."
+ ConfigurationListenerImpl.LISTENER_PID_SUFFIX,
cl.getFactoryPid(4));
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, cl.getType(4));
} finally {
removeConfigurationListener(cl);
tb.uninstall();
}
}
/**
* Tests if a configuration plugin is invoked when only a configuration
* listener is registered (no managed service). It should not be invoked.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec
* ConfigurationPlugin.modifyConfiguration(ServiceReference,Dictionary)
*
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testConfigurationPluginService() throws Exception {
ConfigurationListenerImpl cl = null;
NotVisitablePlugin plugin = null;
String pid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
/* Set up the configuration */
Configuration conf = cm.getConfiguration(pid);
Hashtable props = new Hashtable();
props.put("key", "value1");
SynchronizerImpl synchronizer = new SynchronizerImpl();
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
trace("Create and register a new ConfigurationPlugin");
plugin = createConfigurationPlugin();
conf.update(props);
trace("Wait until the ConfigurationListener has gotten the update");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertTrue("ConfigurationPlugin not visited", plugin.notVisited());
} finally {
removeConfigurationListener(cl);
removeConfigurationPlugin(plugin);
}
}
/**
* Tests if a configuration plugin is invoked when only a configuration
* listener is registered (managed service factory). It should not be
* invoked.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec
* ConfigurationPlugin.modifyConfiguration(ServiceReference,Dictionary)
*
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testConfigurationPluginServiceFactory() throws Exception {
ConfigurationListenerImpl cl = null;
NotVisitablePlugin plugin = null;
String factorypid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
/* Set up the configuration */
Configuration conf = cm.createFactoryConfiguration(factorypid);
Hashtable props = new Hashtable();
props.put("key", "value1");
SynchronizerImpl synchronizer = new SynchronizerImpl();
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
trace("Create and register a new ConfigurationPlugin");
plugin = createConfigurationPlugin();
conf.update(props);
trace("Wait until the ConfigurationListener has gotten the update");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertTrue("ConfigurationPlugin not visited", plugin.notVisited());
} finally {
removeConfigurationListener(cl);
removeConfigurationPlugin(plugin);
}
}
/** *** Helper methods **** */
/**
* creates and registers a configuration listener that expects just one
* event.
*/
private ConfigurationListenerImpl createConfigurationListener(
SynchronizerImpl synchronizer) throws Exception {
return createConfigurationListener(synchronizer, 1);
}
/**
* creates and registers a configuration listener that expects eventCount
* events.
*/
private ConfigurationListenerImpl createConfigurationListener(
SynchronizerImpl synchronizer, int eventCount) throws Exception {
ConfigurationListenerImpl listener = new ConfigurationListenerImpl(
synchronizer, eventCount);
registerService(ConfigurationListener.class.getName(), listener, null);
return listener;
}
/**
* creates and registers a configuration plugin.
*/
private NotVisitablePlugin createConfigurationPlugin() throws Exception {
NotVisitablePlugin plugin = new NotVisitablePlugin();
registerService(ConfigurationPlugin.class.getName(), plugin, null);
return plugin;
}
/**
* unregisters a configuration listener.
*/
private void removeConfigurationListener(ConfigurationListener cl)
throws Exception {
unregisterService(cl);
}
/**
* unregisters a configuration plugin.
*/
private void removeConfigurationPlugin(ConfigurationPlugin plugin)
throws Exception {
unregisterService(plugin);
}
private ManagedServiceImpl createManagedService(String pid, Semaphore s)
throws Exception {
ManagedServiceImpl ms = new ManagedServiceImpl(s);
Hashtable props = new Hashtable();
props.put(Constants.SERVICE_PID, pid);
/* TODO: Testa registered service.pid with other String */
registerService(ManagedService.class.getName(), ms, props);
trace("ManagedService is registered with pid:" + pid);
return ms;
}
private void checkConfiguration(Configuration conf, String message,
String pid, String location) throws BundleException {
assertNotNull(message, conf);
assertEquals("Pid", pid, conf.getPid());
assertNull("FactoryPid", conf.getFactoryPid());
assertNull("Properties", conf.getProperties());
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
}
/**
* See if a configuration is part of a list.
*
* @return index of the list if the configuration is a part of the
* list.Otherwise, return -1nd.
*/
private int isPartOf(Configuration theConf, List configs) {
for (int i = 0; i < configs.size(); i++)
if (equals((Configuration) configs.get(i), theConf))
return i;
return -1;
}
/**
* Compares two Configurations for equality. Configuration.equals() is not
* specified in the spec, so this is a helper method that compares pids.
* <p>
* Two Configurations are considered equal if the got the same pid or if
* both are null.
*/
private boolean equals(Configuration c1, Configuration c2) {
boolean result = false;
/* If both are null, they are equal */
if ((c1 == null) && (c2 == null)) {
result = true;
}
/* If none of them is null, and got the same pid, they are equal */
if ((c1 != null) && (c2 != null)) {
result = c1.getPid().equals(c2.getPid());
}
return result;
}
public final static String PACKAGE = "org.osgi.test.cases.cm.tbc";
private String getLocation() {
return getContext().getBundle().getLocation();
}
/**
* Removes any configurations made by this bundle.
*/
private void cleanCM(Set existingConfigs) throws Exception {
if (cm != null) {
Configuration[] configs = cm.listConfigurations(null);
if (configs != null) {
// log(" cleanCM() -- Checking " + configs.length + " configs");
for (int i = 0; i < configs.length; i++) {
Configuration config = configs[i];
if (!existingConfigs.contains(config.getPid())) {
// log(" Delete " + config.getPid());
config.delete();
} else {
// log(" Keep " + config.getPid());
}
}
} else {
// log(" cleanCM() -- No Configurations to clear");
}
} else {
// log(" cleanCM() -- No CM !");
}
}
class Plugin implements ConfigurationPlugin {
private int index;
Plugin(int x) {
index = x;
}
public void modifyConfiguration(ServiceReference ref, Dictionary props) {
trace("Calling plugin with cmRanking=" + (index * 10));
String[] types = (String[]) ref.getProperty("objectClass");
for (int i = 0; i < types.length; i++) {
if ("org.osgi.service.cm.ManagedService".equals(types[i])) {
props.put("plugin.ms." + index, "added by plugin#" + index);
break;
} else if ("org.osgi.service.cm.ManagedServiceFactory"
.equals(types[i])) {
props.put("plugin.factory." + index, "added by plugin#"
+ index);
break;
}
}
}
}
/**
* <code>ConfigurationPlugin</code> implementation to be used in the
* <code>ConfigurationListener</code> test. The plugin should NOT be invoked
* when there's no <code>ManagedService</code> or
* <code>ManagedServiceFactory</code> registered.
*/
class NotVisitablePlugin implements ConfigurationPlugin {
private boolean visited;
/**
* Creates a <code>ConfigurationPlugin</code> instance that has not been
* invoked (visited) by a <code>Configuration</code> update event.
*
*/
public NotVisitablePlugin() {
visited = false;
}
/**
* <p>
* Callback method when a <code>Configuration</code> update is being
* delivered to a registered <code>ManagedService</code> or
* <code>ManagedServiceFactory</code> instance.
* </p>
* <p>
* Set plugin to visited (<code>visited = true</code>) when this method
* is invoked. If this happens, the <code>ConfigurationListener</code>
* tests failed.
* </p>
*
* @param ref
* the <code>ConfigurationAdmin</code> that generated the
* update.
* @param props
* the <code>Dictionary</code> containing the properties of
* the <code>
* @see org.osgi.service.cm.ConfigurationPlugin#modifyConfiguration(org.osgi.framework.ServiceReference,
* java.util.Dictionary)
*/
public void modifyConfiguration(ServiceReference ref, Dictionary props) {
visited = true;
}
/**
* Checks if the plugin has not been invoked by a <code>Configuration
* </code> update event.
*
* @return <code>true</code> if plugin has not been visited (invoked).
* <code>false</code>, otherwise.
*/
public boolean notVisited() {
return !visited;
}
}
/**
* <code>ConfigurationPlugin</code> implementation to be used in the
* <code>ConfigurationListener</code> test. The plugin should NOT be invoked
* when there's no <code>ManagedService</code> or
* <code>ManagedServiceFactory</code> registered.
*/
class RunnableImpl implements Runnable {
private final String pid;
private String location;
private Configuration conf;
private Object lock = new Object();
RunnableImpl(String pid, String location) {
this.pid = pid;
this.location = location;
}
Configuration getConfiguration() {
return conf;
}
public void run() {
try {
Sleep.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conf = cm.getConfiguration(pid, location);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Sleep.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conf.setBundleLocation(location);
}
void unlock() {
synchronized (lock) {
lock.notifyAll();
}
}
void unlock(String newLocation) {
location = newLocation;
synchronized (lock) {
lock.notifyAll();
}
}
}
class SyncEventListener implements SynchronousConfigurationListener {
private final Synchronizer sync;
public SyncEventListener(final Synchronizer sync) {
this.sync = sync;
}
public void configurationEvent(ConfigurationEvent event) {
this.sync.signal();
}
}
/*
* Shigekuni KONDO, Ikuo YAMASAKI, (Yushi Kuroda), NTT Corporation adds
* tests for specification version 1.4
*/
private final String locationA = "location.a";
private final String locationB = "location.b";
private final String regionA = "?RegionA";
private String regionB = "?RegionB";
public void testGetConfigurationWithLocation_2_01() throws Exception {
final String locationOld = null;
this.internalGetConfigurationWithLocation_2_02To08(1, locationOld);
}
public void testGetConfigurationWithLocation_2_02() throws Exception {
final String locationOld = locationA;
this.internalGetConfigurationWithLocation_2_02To08(2, locationOld);
}
public void testGetConfigurationWithLocation_2_03() throws Exception {
final String locationOld = locationA + "*";
this.internalGetConfigurationWithLocation_2_02To08(3, locationOld);
}
public void testGetConfigurationWithLocation_2_04() throws Exception {
final String locationOld = locationB;
this.internalGetConfigurationWithLocation_2_02To08(4, locationOld);
}
public void testGetConfigurationWithLocation_2_06() throws Exception {
final String locationOld = "?*";
this.internalGetConfigurationWithLocation_2_02To08(6, locationOld);
}
public void testGetConfigurationWithLocation_2_07() throws Exception {
final String locationOld = regionA;
this.internalGetConfigurationWithLocation_2_02To08(7, locationOld);
}
public void testGetConfigurationWithLocation_2_08() throws Exception {
final String locationOld = regionB;
this.internalGetConfigurationWithLocation_2_02To08(8, locationOld);
}
public void internalGetConfigurationWithLocation_2_02To08(final int minor,
final String locationOld) throws BundleException, IOException {
final String header = "testGetConfigurationWithLocation_2_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
this.setAppropriatePermission();
final String pid1 = Util.createPid("1");
Configuration conf = null;
Dictionary props = new Hashtable();
// Get a brand new configuration
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// micro 2
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// micro 1
testId = traceTestId(header, ++micro);
props.put("StringKey", "stringvalue");
conf.update(props);
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// micro 4
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 2) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
// micro 3
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 2) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
// micro 8
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 6 || minor == 7 || minor == 8) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
// micro 7
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 6 || minor == 7 || minor == 8) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
// micro 10
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 7) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
// micro 9
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 7) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
// micro 12
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, locationOld);
// micro 11
testId = traceTestId(header, ++micro);
conf.update(props);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, locationOld);
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
// micro 13
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add("?");
cList.add(regionA);
setCPListtoBundle(cList, null, thisBundle);
conf.update(props);
if (minor == 7) {
conf = cm.getConfiguration(pid1, "?");
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, "?");
}
conf.delete();
if (minor == 2) {
resetPermissions();
conf = cm.getConfiguration(pid1, thisLocation);
// micro 16
testId = traceTestId(header, ++micro);
setCPtoBundle(null, null, thisBundle);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// micro 15
testId = traceTestId(header, ++micro);
conf.update(props);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
conf.delete();
}
}
// TODO confirm
public void testGetConfigurationWithLocation_2_09() throws Exception {
final String locationOld = null;
this.internalGetConfigurationWithLocation_2_09To13(9, locationOld);
}
public void testGetConfigurationWithLocation_2_10() throws Exception {
final String locationOld = locationA;
this.internalGetConfigurationWithLocation_2_09To13(10, locationOld);
}
public void testGetConfigurationWithLocation_2_12() throws Exception {
final String locationOld = regionA;
this.internalGetConfigurationWithLocation_2_09To13(12, locationOld);
}
public void testGetConfigurationWithLocation_2_13() throws Exception {
final String locationOld = regionA + "*";
this.internalGetConfigurationWithLocation_2_09To13(13, locationOld);
}
public void internalGetConfigurationWithLocation_2_09To13(final int minor,
final String location) throws BundleException, IOException {
final String header = "testGetConfigurationWithLocation_2_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
this.setAppropriatePermission();
final String pid1 = Util.createPid("1");
Configuration conf = null;
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf = cm.getConfiguration(pid1, location);
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 10) {
conf = cm.getConfiguration(pid1, location);
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
}
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle(locationB, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("?", ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
// 5
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 12 || minor == 13) {
conf = cm.getConfiguration(pid1, location);
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
}
// 6
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 12) {
conf = cm.getConfiguration(pid1, location);
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
}
// 7
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
if (minor == 10) {
// thisLocation no permission
testId = traceTestId(header, ++micro);
setCPtoBundle(null, null, thisBundle);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
// thisLocation with CONFIGURE
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE,
thisBundle);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
// thisLocation with TARGET
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
}
}
private void setCPtoBundle(String name, String action, Bundle bundle)
throws BundleException {
this.setCPtoBundle(name, action, bundle, true);
}
private void setCPtoBundle(String name, String action, Bundle bundle,
boolean resetAll) throws BundleException {
if (resetAll)
this.resetPermissions();
list.clear();
add(list, PropertyPermission.class.getName(), "*", "READ,WRITE");
add(list, PP, "*", "IMPORT,EXPORTONLY");
add(list, SP, "*", "GET,REGISTER");
if (name != null && action != null)
add(list, CP, name, action);
add(list, AP, "*", "*");
permissionFlag = true;
this.setBundlePermission(bundle, list);
}
private void resetBundlePermission(Bundle b, List list) throws BundleException {
this.resetPermissions();
if (list != null) {
this.setBundlePermission(b, list);
}
}
private String traceTestId(final String header, int micro) {
String testId = header + String.valueOf(micro);
trace(testId);
return testId;
}
private void assertThrowsSEbyGetConfigurationWithLocation(String testId,
String pid, String location) {
String message = testId
+ ":try to get configuration without appropriate ConfigurationPermission.";
try {
cm.getConfiguration(pid, location);
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
public void testGetConfiguration_3_01() throws Exception {
final String locationOld = null;
this.internalGetConfiguration_3_01To07(1, locationOld);
}
public void testGetConfiguration_3_02() throws Exception {
final String locationOld = locationA;
this.internalGetConfiguration_3_01To07(2, locationOld);
}
public void testGetConfiguration_3_03() throws Exception {
final String locationOld = locationA + "*";
this.internalGetConfiguration_3_01To07(3, locationOld);
}
public void testGetConfiguration_3_04() throws Exception {
final String locationOld = locationB;
this.internalGetConfiguration_3_01To07(4, locationOld);
}
public void testGetConfiguration_3_06() throws Exception {
final String locationOld = regionA;
this.internalGetConfiguration_3_01To07(6, locationOld);
}
public void testGetConfiguration_3_07() throws Exception {
final String locationOld = regionA + "*";
this.internalGetConfiguration_3_01To07(7, locationOld);
}
public void internalGetConfiguration_3_01To07(int minor, String locationOld)
throws BundleException, IOException {
final String header = "testGetConfiguration_3_" + String.valueOf(minor)
+ "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
Dictionary props = new Hashtable();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
String message = testId
+ ":try to get configuration with appropriate ConfigurationPermission.";
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf = cm.getConfiguration(pid1);
if (minor == 1) {
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
}
// 1
testId = traceTestId(header, ++micro);
props.put("StringKey", "stringvalue");
conf.update(props);
conf = cm.getConfiguration(pid1);
if (minor == 1) {
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
}
conf.delete();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else if (minor == 2) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
// 3
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else if (minor == 2) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
conf.delete();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 8
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else if (minor == 6 || minor == 7) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
// 7
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else if (minor == 6 || minor == 7) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
conf.delete();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 10
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else if (minor == 6) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
// 9
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else if (minor == 6) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
conf.delete();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 12
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
// 11
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
conf.delete();
if (minor == 1) {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 15
testId = traceTestId(header, ++micro);
setCPtoBundle(null, null, thisBundle);
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// 14
testId = traceTestId(header, ++micro);
conf.update(props);
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
conf.delete();
}
if (minor == 2) {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, thisLocation);
// 15
testId = traceTestId(header, ++micro);
setCPtoBundle(null, null, thisBundle);
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// 14
testId = traceTestId(header, ++micro);
conf.update(props);
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
conf.delete();
}
}
private void assertThrowsSEbyGetConfiguration(final String pid,
String message) throws AssertionFailedError {
try {
cm.getConfiguration(pid);
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
// TODO confirm
public void testCreateFactoryConfiguration_4_01() throws Exception {
String location = null;
this.internalCreateFactoryConfigurationWithLocation_4_01To07(1,
location);
}
public void testCreateFactoryConfiguration_4_02() throws Exception {
String location = locationA;
this.internalCreateFactoryConfigurationWithLocation_4_01To07(2,
location);
}
public void testCreateFactoryConfiguration_4_03() throws Exception {
String location = locationA + "*";
this.internalCreateFactoryConfigurationWithLocation_4_01To07(3,
location);
}
public void testCreateFactoryConfiguration_4_04() throws Exception {
String location = locationB;
this.internalCreateFactoryConfigurationWithLocation_4_01To07(4,
location);
}
public void testCreateFactoryConfiguration_4_06() throws Exception {
String location = regionA;
this.internalCreateFactoryConfigurationWithLocation_4_01To07(6,
location);
}
public void testCreateFactoryConfiguration_4_07() throws Exception {
String location = regionA + "*";
this.internalCreateFactoryConfigurationWithLocation_4_01To07(7,
location);
}
public void internalCreateFactoryConfigurationWithLocation_4_01To07(
int minor, String location) throws BundleException, IOException {
final String header = "testCreateFactoryConfigurationWithLocation_4_"
+ String.valueOf(minor) + "_";
;
String fpid = Util.createPid("factory1");
String testId = null;
int micro = 0;
String message = testId
+ ":try to create factory configuration with location with inappropriate ConfigurationPermission.";
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
Configuration conf1 = cm.createFactoryConfiguration(fpid, location);
Configuration conf2 = cm.createFactoryConfiguration(fpid, location);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf2));
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 2) {
conf1 = cm.createFactoryConfiguration(fpid, location);
conf2 = cm.createFactoryConfiguration(fpid, location);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf2));
} else {
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
}
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 6 || minor == 7) {
conf1 = cm.createFactoryConfiguration(fpid, location);
conf2 = cm.createFactoryConfiguration(fpid, location);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf2));
} else {
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
}
// 5
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 6) {
conf1 = cm.createFactoryConfiguration(fpid, location);
conf2 = cm.createFactoryConfiguration(fpid, location);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf2));
} else {
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
}
// 6
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
// 7
if (minor == 6) {
testId = traceTestId(header, ++micro);
setCPtoBundle(regionB, ConfigurationPermission.CONFIGURE,
thisBundle);
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
}
// 8
if (minor == 2) {
traceTestId(header, ++micro);
this.resetPermissions();
setCPtoBundle(null, null, thisBundle);
conf1 = cm.createFactoryConfiguration(fpid, thisLocation);
conf2 = cm.createFactoryConfiguration(fpid, thisLocation);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", thisLocation,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", thisLocation,
this.getBundleLocationForCompare(conf2));
}
}
private void assertThrowsSEbyCreateFactoryConf(final String fPid,
final String location, String message) throws AssertionFailedError {
try {
cm.createFactoryConfiguration(fPid, location);
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
public void testListConfigurations_6_01() throws Exception {
String filter = null;
this.internalListConfigurations(1, filter);
}
public void testListConfigurations_6_02() throws Exception {
String filter = "(service.pid=pid1)";
this.internalListConfigurations(2, filter);
}
public void testListConfigurations_6_03() throws Exception {
String filter = "(service.bundleLocation=location.a)";
this.internalListConfigurations(3, filter);
}
public void testListConfigurations_6_04() throws Exception {
String filter = "(service.bundleLocation=?RegionA)";
this.internalListConfigurations(4, filter);
}
public void testListConfigurations_6_05() throws Exception {
String filter = "(&(service.bundleLocation=?RegionA)(service.pid=pid2))";
this.internalListConfigurations(5, filter);
}
public void internalListConfigurations(int minor, String filter)
throws IOException, InvalidSyntaxException, BundleException {
final String header = "testListConfigurations_6_"
+ String.valueOf(minor) + "_";
int micro = 0;
String testId = null;
String pid1 = "pid1";
String pid2 = "pid2";
String pid3 = "pid3";
Configuration conf1 = null;
Configuration conf2 = null;
Configuration conf3 = null;
Dictionary prop = new Hashtable();
prop.put("StringKey", "Stringvalue");
String message = testId + ":try listConfigurations ";
this.setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf1 = cm.getConfiguration(pid1, locationA);
conf1.update(prop);
conf2 = cm.getConfiguration(pid2, regionA);
conf2.update(prop);
conf3 = cm.getConfiguration(pid3, "?");
conf3.update(prop);
testId = traceTestId(header, ++micro);
this.setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE,
thisBundle);
Configuration[] conflist = cm.listConfigurations(filter);
if (minor == 4 || minor == 5) {
assertNull("Returned list of configuration MUST be null.", conflist);
} else {
assertEquals("number of Configuration Object", 1, conflist.length);
assertEquals(message, conflist[0], conf1);
}
testId = traceTestId(header, ++micro);
this.setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE,
thisBundle);
conflist = cm.listConfigurations(filter);
if (minor == 1 || minor == 4 || minor == 5) {
assertEquals("number of Configuration Object", 1, conflist.length);
assertEquals(message, conflist[0], conf2);
} else {
assertNull("Returned list of configuration MUST be null.", conflist);
}
}
// TODO
public void testGetBundleLocation_7_01() throws Exception {
String locationOld = null;
this.internalGetBundleLocation_7_01to08(1, locationOld);
}
public void testGetBundleLocation_7_02() throws Exception {
String locationOld = locationA;
this.internalGetBundleLocation_7_01to08(2, locationOld);
}
public void testGetBundleLocation_7_03() throws Exception {
String locationOld = locationA + "*";
this.internalGetBundleLocation_7_01to08(3, locationOld);
}
public void testGetBundleLocation_7_05() throws Exception {
String locationOld = "?*";
this.internalGetBundleLocation_7_01to08(5, locationOld);
}
public void testGetBundleLocation_7_06() throws Exception {
String locationOld = regionA;
this.internalGetBundleLocation_7_01to08(6, locationOld);
}
public void testGetBundleLocation_7_07() throws Exception {
String locationOld = regionA + "*";
this.internalGetBundleLocation_7_01to08(7, locationOld);
}
public void testGetBundleLocation_7_08() throws Exception {
String locationOld = thisLocation;
this.internalGetBundleLocation_7_01to08(8, locationOld);
}
public void internalGetBundleLocation_7_01to08(final int minor,
final String locationOld) throws Exception {
final String header = "testGetBundleLocation_7_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
String loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE,
thisBundle);
if (minor == 2) {
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
} else {
this.assertThrowsSEbyGetLocation(conf, testId);
}
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("?", ConfigurationPermission.CONFIGURE, thisBundle);
this.assertThrowsSEbyGetLocation(conf, testId);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 5 || minor == 6 || minor == 7) {
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
} else {
this.assertThrowsSEbyGetLocation(conf, testId);
}
// 5
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE,
thisBundle);
if (minor == 6) {
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
} else {
this.assertThrowsSEbyGetLocation(conf, testId);
}
// 6
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
this.assertThrowsSEbyGetLocation(conf, testId);
// 7
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE + ","
+ ConfigurationPermission.TARGET, thisBundle);
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
// 8
if (minor == 6 || minor == 7) {
testId = traceTestId(header, ++micro);
setCPtoBundle(regionB, ConfigurationPermission.CONFIGURE,
thisBundle);
this.assertThrowsSEbyGetLocation(conf, testId);
}
++micro;
// 9
if (minor == 6) {
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE + ","
+ ConfigurationPermission.TARGET, thisBundle);
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
}
++micro;
// 10
testId = traceTestId(header, ++micro);
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, thisLocation);
// Bug2539: need to have CONFIGURE(thisLocation)
setCPtoBundle(thisLocation, ConfigurationPermission.CONFIGURE, thisBundle);
loc = conf.getBundleLocation();
assertEquals("Check conf location", thisLocation, loc);
} finally {
this.resetPermissions();
if (conf != null)
conf.delete();
}
}
private void assertThrowsSEbyGetLocation(final Configuration conf,
String testId) throws AssertionFailedError {
String message = testId
+ ":try to get bundle location without appropriate ConfigurationPermission.";
try {
conf.getBundleLocation();
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
public void testSetBundleLocation_8_01() throws Exception {
String locationOld = null;
String location = null;
this.internalSetBundleLocation_8_01to07(1, locationOld, location);
}
public void testSetBundleLocation_8_02() throws Exception {
String locationOld = null;
String location = locationA;
this.internalSetBundleLocation_8_01to07(2, locationOld, location);
}
public void testSetBundleLocation_8_04() throws Exception {
String locationOld = null;
String location = "?*";
this.internalSetBundleLocation_8_01to07(4, locationOld, location);
}
public void testSetBundleLocation_8_05() throws Exception {
String locationOld = null;
String location = regionA;
this.internalSetBundleLocation_8_01to07(5, locationOld, location);
}
public void testSetBundleLocation_8_06() throws Exception {
String locationOld = locationA;
String location = null;
this.internalSetBundleLocation_8_01to07(6, locationOld, location);
}
public void testSetBundleLocation_8_07() throws Exception {
String locationOld = locationA;
String location = locationA;
this.internalSetBundleLocation_8_01to07(7, locationOld, location);
}
public void internalSetBundleLocation_8_01to07(final int minor,
final String locationOld, final String location) throws Exception {
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 2
testId = traceTestId(header, ++micro);
if (minor == 6 || minor == 7) {
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE,
thisBundle);
if (minor == 7) {
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
} else
assertThrowsSEbySetLocation(conf, location, testId);
} else {
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
}
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_08() throws Exception {
int minor = 8;
String locationOld = locationA;
String location = locationB;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add(locationA);
cList.add(locationB);
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle(locationB, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(locationOld);
// 5
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_10() throws Exception {
int minor = 10;
String locationOld = locationA;
String location = regionA;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add(locationA);
cList.add(regionA);
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_15() throws Exception {
int minor = 15;
String locationOld = regionA;
String location = null;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_16() throws Exception {
int minor = 16;
String locationOld = regionA;
String location = locationA;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add(locationA);
cList.add(regionA);
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_17() throws Exception {
int minor = 17;
String locationOld = regionA;
String location = "?";
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add("?");
cList.add(regionA);
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("?", ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_18() throws Exception {
int minor = 18;
String locationOld = regionA;
String location = regionA;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle("?", ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_19() throws Exception {
int minor = 19;
String locationOld = locationA + "*";
String location = regionA + "*";
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add(locationA + "*");
cList.add(regionA + "*");
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
// 2
testId = traceTestId(header, ++micro);
cList = new ArrayList();
cList.add(locationA + ".com");
cList.add(regionA + ".com");
setCPListtoBundle(cList, null, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
private void setCPListtoBundle(List nameforConfigure, List nameForTarget,
Bundle bundle) throws BundleException {
this.resetPermissions();
list.clear();
add(list, PropertyPermission.class.getName(), "*", "READ,WRITE");
add(list, PP, "*", "IMPORT,EXPORTONLY");
add(list, SP, "*", "GET,REGISTER");
add(list, AP, "*", "*");
if (nameforConfigure != null)
if (!nameforConfigure.isEmpty()) {
for (Iterator itc = nameforConfigure.iterator(); itc.hasNext();) {
add(list, CP, (String) itc.next(),
ConfigurationPermission.CONFIGURE);
}
}
if (nameForTarget != null)
if (!nameForTarget.isEmpty()) {
for (Iterator itt = nameforConfigure.iterator(); itt.hasNext();) {
add(list, CP, (String) itt.next(),
ConfigurationPermission.TARGET);
}
}
permissionFlag = true;
this.setBundlePermission(bundle, list);
}
private void assertThrowsSEbySetLocation(final Configuration conf,
final String location, String testId) throws AssertionFailedError {
String message = testId
+ ":try to set bundle location without appropriate ConfigurationPermission.";
try {
conf.setBundleLocation(location);
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
/* Ikuo YAMASAKI */
private int assertCallback(SynchronizerImpl sync, int count) {
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue(
"ManagedService#updated(props)/ManagedServiceFactory#updated(pid,props) must be called back",
calledback);
return count;
}
private void assertNoCallback(SynchronizerImpl sync, int count) {
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
assertFalse(
"ManagedService#updated(props)/ManagedServiceFactory#updated(pid,props) must NOT be called back",
calledback);
}
private int assertDeletedCallback(SynchronizerImpl sync, int count) {
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count,
true);
assertTrue("ManagedServiceFactory#deleted(pid) must be called back",
calledback);
return count;
}
private void assertDeletedNoCallback(SynchronizerImpl sync, int count) {
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1,
true);
assertFalse(
"ManagedServiceFactory#deleted(pid) must NOT be called back",
calledback);
}
private void cleanUpForCallbackTest(final Bundle bundleT1,
final Bundle bundleT2, final Bundle bundleT3, List list)
throws BundleException {
this.cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, null, list);
}
private void cleanUpForCallbackTest(final Bundle bundleT1,
final Bundle bundleT2, final Bundle bundleT3,
final Bundle bundleT4, List list) throws BundleException {
for (Iterator regs = list.iterator(); regs.hasNext();)
((ServiceRegistration) regs.next()).unregister();
list.clear();
if (bundleT1 != null)
bundleT1.uninstall();
if (bundleT2 != null)
bundleT2.uninstall();
if (bundleT3 != null)
bundleT3.uninstall();
if (bundleT4 != null)
bundleT4.uninstall();
}
/**
*
* @throws Exception
*/
public void testManagedServiceRegistration9_1_1() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(3);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testSetBundleLocation_9_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.setCPtoBundle(null, null, bundleT1, false);
this.startTargetBundle(bundleT1);
// this.setInappropriatePermission();
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
this.setAppropriatePermission();
Configuration conf = cm.getConfiguration(pid1,
bundleT1.getLocation());
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_1);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("Conf is being deleted.");
conf.delete();
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
private void restartCM() throws BundleException {
Bundle cmBundle = stopCmBundle();
cmBundle.stop();
trace("CM has been stopped.");
startCmBundle(cmBundle);
trace("CM has been started.");
}
/**
*
* @throws Exception
*/
public void testManagedServiceRegistration9_1_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(3);
/*
* A. create Configuration in advance, Then Register ManagedService .
*/
final String header = "testSetBundleLocation_9_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, bundleT1.getLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.setCPtoBundle(null, null, bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("null props must be called back", sync1_1.getProps());
assertEquals("Check props", "stringvalue",
sync1_1.getProps().get("StringKey"));
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("Conf is being deleted.");
conf.delete();
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
/**
*
* @throws Exception
*/
// public void testManagedServiceRegistration9_2_1() throws Exception {
// final Bundle bundleT1 = getContext().installBundle(
// getWebServer() + "bundleT1.jar");
// final Bundle bundleT2 = getContext().installBundle(
// getWebServer() + "bundleT2.jar");
// final String locationT2 = bundleT2.getLocation();
// final String pid1 = Util.createPid("pid1");
// List list = new ArrayList(3);
// /*
// * A. Register ManagedService in advance. Then create Configuration.
// */
// final String header = "testSetBundleLocation_9_2_1";
//
// String testId = null;
// int micro = 0;
// testId = traceTestId(header, ++micro);
//
// this.setCPtoBundle(locationT2, "target", bundleT1);
//
// try {
// SynchronizerImpl sync1_1 = new SynchronizerImpl();
// list.add(getContext().registerService(Synchronizer.class.getName(),
// sync1_1, propsForSync1_1));
// SynchronizerImpl sync1_2 = new SynchronizerImpl();
// list.add(getContext().registerService(Synchronizer.class.getName(),
// sync1_2, propsForSync1_2));
// this.startTargetBundle(bundleT1);
// trace("Wait for signal.");
// int count1_1 = 0;
// count1_1 = assertCallback(sync1_1, count1_1);
// assertNull("called back with null props", sync1_1.getProps());
// int count1_2 = 0;
// count1_2 = assertCallback(sync1_2, count1_2);
// assertNull("called back with null props", sync1_2.getProps());
//
// trace("The configuration is being created");
//
// Configuration conf = cm.getConfiguration(pid1, bundleT2
// .getLocation());
// trace("Wait for signal.");
// assertNoCallback(sync1_1, count1_1);
//
// trace("The configuration is being updated ");
// Dictionary props = new Hashtable();
// props.put("StringKey", "stringvalue");
// conf.update(props);
// trace("Wait for signal.");
// assertNoCallback(sync1_1, count1_1);
// assertNoCallback(sync1_2, count1_2);
//
// // restartCM();
// // conf = cm.getConfiguration(pid1, bundleT2.getLocation());
// // trace("Wait for signal.");
// // count1_1 = assertCallback(sync1_1, count1_1);
// // count1_2 = assertCallback(sync1_2, count1_2);
// // assertNull("called back with null props", sync1_2.getProps());
// //
// // trace("conf is going to be deleted.");
// // conf.delete();
// // count1_1 = assertCallback(sync1_1, count1_1);
// // assertNull("called back with null props", sync1_1.getProps());
// // this.assertNoCallback(sync1_2, count1_2);
//
// } finally {
// this.cleanUpForCallbackTest(bundleT1, null, null, list);
// }
// }
//
public void testManagedServiceRegistration9_2_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
internalManagedServiceRegistration9_2_1to2(2, bundleT2.getLocation(),
ConfigurationPermission.TARGET, bundleT1, bundleT2);
}
public void testManagedServiceRegistration9_2_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
internalManagedServiceRegistration9_2_1to2(3, "*",
ConfigurationPermission.TARGET, bundleT1, bundleT2);
}
private void internalManagedServiceRegistration9_2_1to2(final int micro,
final String target, final String actions, final Bundle bundleT1,
final Bundle bundleT2) throws Exception {
final String locationT2 = bundleT2.getLocation();
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(3);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testSetBundleLocation_9_2_"
+ String.valueOf(micro);
String testId = null;
int micro1 = 0;
testId = traceTestId(header, ++micro1);
this.setCPtoBundle(actions, target, bundleT1);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1,
bundleT2.getLocation());
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("conf is going to be deleted.");
conf.delete();
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
/**
*
* @throws Exception
*/
public void testManagedServiceRegistration9_2_4() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
internalManagedServiceRegistration9_2_4to5(4, bundleT2.getLocation(),
"target", bundleT1, bundleT2);
}
public void testManagedServiceRegistration9_2_5() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
internalManagedServiceRegistration9_2_4to5(5, "*", "target", bundleT1,
bundleT2);
}
public void internalManagedServiceRegistration9_2_4to5(final int micro,
final String target, final String actions, final Bundle bundleT1,
final Bundle bundleT2) throws Exception {
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(3);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testSetBundleLocation_9_2_"
+ String.valueOf(micro);
int micro1 = 0;
String testId = traceTestId(header, ++micro1);
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, bundleT2.getLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
this.setCPtoBundle(target, actions, bundleT1);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("Conf is being deleted.");
conf.delete();
this.assertNoCallback(sync1_1, count1_1);
this.assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, null, list);
}
}
/**
* Register ManagedService in advance. Then create Configuration.
*
* @throws Exception
*/
public void testManagedServiceRegistrationMultipleTargets_10_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final Bundle bundleT4 = getContext().installBundle(
getWebServer() + "bundleT4.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(7);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testManagedServiceRegistrationMultipleTargets_10_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSync3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSync3_2));
SynchronizerImpl sync4_1 = new SynchronizerImpl("4-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_1, propsForSync4_1));
SynchronizerImpl sync4_2 = new SynchronizerImpl("4-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_2, propsForSync4_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?*", "target", bundleT2, false);
this.setCPtoBundle("?RegionA", "target", bundleT3, false);
this.setCPtoBundle("?RegionA", "target", bundleT4, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
int count3_1 = 0;
count3_1 = assertCallback(sync3_1, count3_1);
assertNull("called back with null props", sync3_1.getProps());
int count3_2 = 0;
count3_2 = assertCallback(sync3_2, count3_2);
assertNull("called back with null props", sync3_2.getProps());
this.startTargetBundle(bundleT4);
// TODO Called back twice each pid.
// int count4_1 = 0;
int count4_1 = 1;
count4_1 = assertCallback(sync4_1, count4_1);
assertNull("called back with null props", sync4_1.getProps());
// count4_1 = 2
// int count4_2 = 0;
int count4_2 = 1;
count4_2 = assertCallback(sync4_2, count4_2);
assertNull("called back with null props", sync4_2.getProps());
// count4_2 = 2
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
assertNoCallback(sync4_1, count4_1);
assertNoCallback(sync4_2, count4_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNotNull("called back with Non-null props", sync2_1.getProps());
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
count4_1 = assertCallback(sync4_1, count4_1);
assertNotNull("called back with Non-null props", sync4_1.getProps());
assertNoCallback(sync4_2, count4_2);
trace("conf is going to be deleted.");
conf.delete();
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
count3_1 = assertCallback(sync3_1, count3_1);
assertNull("called back with null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNull("called back with null props", sync3_2.getProps());
count4_1 = assertCallback(sync4_1, count4_1);
assertNull("called back with null props", sync4_1.getProps());
assertNoCallback(sync4_2, count4_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, bundleT4, list);
}
}
/**
* Register ManagedService in advance. Then create Configuration.
*
* @throws Exception
*/
public void testManagedServiceRegistrationMultipleTargets_10_1_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final Bundle bundleT4 = getContext().installBundle(
getWebServer() + "bundleT4.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testManagedServiceRegistrationMultipleTargets_10_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSync3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSync3_2));
SynchronizerImpl sync4_1 = new SynchronizerImpl("4-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_1, propsForSync4_1));
SynchronizerImpl sync4_2 = new SynchronizerImpl("4-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_2, propsForSync4_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle("?RegionB", "target", bundleT3, false);
this.setCPtoBundle("?RegionA", "target", bundleT4, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
int count3_1 = 0;
count3_1 = assertCallback(sync3_1, count3_1);
assertNull("called back with null props", sync3_1.getProps());
int count3_2 = 0;
count3_2 = assertCallback(sync3_2, count3_2);
assertNull("called back with null props", sync3_2.getProps());
this.startTargetBundle(bundleT4);
// int count4_1 = 0;
int count4_1 = 1;
count4_1 = assertCallback(sync4_1, count4_1);
assertNull("called back with null props", sync4_1.getProps());
// int count4_2 = 0;
int count4_2 = 1;
count4_2 = assertCallback(sync4_2, count4_2);
assertNull("called back with null props", sync4_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
assertNoCallback(sync4_1, count4_1);
assertNoCallback(sync4_2, count4_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
count4_1 = assertCallback(sync4_1, count4_1);
assertNotNull("called back with Non-null props", sync4_1.getProps());
assertNoCallback(sync4_2, count4_2);
trace("conf is going to be deleted.");
conf.delete();
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
count4_1 = assertCallback(sync4_1, count4_1);
assertNull("called back with null props", sync4_1.getProps());
assertNoCallback(sync4_2, count4_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, bundleT4, list);
}
}
public void testManagedServiceRegistrationMultipleTargets_10_2_1()
throws Exception {
System.setProperty("org.osgi.test.cases.cm.bundleT4.mode","Array" );
try {
this.internalTestManagedServiceRegistrationMultipleTargets_10_2_1to3();
} finally {
System.getProperties().remove("org.osgi.test.cases.cm.bundleT4.mode");
}
}
public void testManagedServiceRegistrationMultipleTargets_10_2_2()
throws Exception {
System.setProperty("org.osgi.test.cases.cm.bundleT4.mode", "Vector");
try {
this.internalTestManagedServiceRegistrationMultipleTargets_10_2_1to3();
} finally {
System.getProperties().remove("org.osgi.test.cases.cm.bundleT4.mode");
}
}
public void testManagedServiceRegistrationMultipleTargets_10_2_3()
throws Exception {
System.setProperty("org.osgi.test.cases.cm.bundleT4.mode", "List");
try {
this.internalTestManagedServiceRegistrationMultipleTargets_10_2_1to3();
} finally {
System.getProperties().remove("org.osgi.test.cases.cm.bundleT4.mode");
}
}
private void internalTestManagedServiceRegistrationMultipleTargets_10_2_1to3()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final Bundle bundleT4 = getContext().installBundle(
getWebServer() + "bundleT4.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceRegistrationMultipleTargets_10_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSync3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSync3_2));
SynchronizerImpl sync4_1 = new SynchronizerImpl("4-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_1, propsForSync4_1));
SynchronizerImpl sync4_2 = new SynchronizerImpl("4-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_2, propsForSync4_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?*", "target", bundleT2, false);
this.setCPtoBundle("?RegionA", "target", bundleT3, false);
this.setCPtoBundle("?RegionA", "target", bundleT4, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with NON-null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
int count3_1 = 0;
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with NON-null props", sync3_1.getProps());
int count3_2 = 0;
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with NON-null props", sync3_2.getProps());
this.startTargetBundle(bundleT4);
trace("Wait for signal.");
// MS for pid2, pid1; two callbacks expected
int count4_1 = 0;
count4_1 = assertCallback(sync4_1, count4_1+1);
assertEquals("expect two callbacks", count4_1, 2);
assertNotNull("called back with NON-null props", sync4_1.getProps());
// MS for pid2, pid3; two callbacks expected
int count4_2 = 0;
count4_2 = assertCallback(sync4_2, count4_2+1);
assertEquals("expect two callbacks", count4_2, 2);
assertNull("called back with null props", sync4_2.getProps());
// trace("conf is going to be deleted.");
// conf.delete();
// assertNoCallback(sync1_1, count1_1);
// assertNoCallback(sync1_2, count1_2);
// count2_1 = assertCallback(sync2_1, count2_1);
// assertNull("called back with null props", sync2_1.getProps());
// count3_1 = assertCallback(sync3_1, count3_1);
// assertNull("called back with null props", sync3_1.getProps());
// count3_2 = assertCallback(sync3_2, count3_2);
// assertNull("called back with null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, bundleT4, list);
}
}
public void testManagedServiceRegistrationMultipleTargets_10_2_4()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final Bundle bundleT4 = getContext().installBundle(
getWebServer() + "bundleT4.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testManagedServiceRegistrationMultipleTargets_10_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSync3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSync3_2));
SynchronizerImpl sync4_1 = new SynchronizerImpl("4-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_1, propsForSync4_1));
SynchronizerImpl sync4_2 = new SynchronizerImpl("4-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_2, propsForSync4_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle("?RegionB", "target", bundleT3, false);
this.setCPtoBundle("?RegionA", "target", bundleT4, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
trace("Wait for signal.");
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
trace("Wait for signal.");
int count3_1 = 0;
count3_1 = assertCallback(sync3_1, count3_1);
assertNull("called back with null props", sync3_1.getProps());
// assertNotNull("called back with NON-null props",
// sync3_1.getProps());
int count3_2 = 0;
count3_2 = assertCallback(sync3_2, count3_2);
assertNull("called back with null props", sync3_2.getProps());
String mode = System
.getProperty("org.osgi.test.cases.cm.bundleT4.mode");
System.out.println("##########################" + mode);
this.startTargetBundle(bundleT4);
trace("Wait for signal.");
int count4_1 = 0;
count4_1 = assertCallback(sync4_1, count4_1);
// ignore actual call back properties, might already have been overwritten
count4_1 = assertCallback(sync4_1, count4_1);
assertNotNull("called back with NON-null props", sync4_1.getProps());
int count4_2 = 0;
count4_2 = assertCallback(sync4_2, count4_2);
// ignore actual call back properties, might already have been overwritten
count4_2 = assertCallback(sync4_2, count4_2);
assertNull("called back with null props", sync4_2.getProps());
// trace("conf is going to be deleted.");
// conf.delete();
// assertNoCallback(sync1_1, count1_1);
// assertNoCallback(sync1_2, count1_2);
// count2_1 = assertCallback(sync2_1, count2_1);
// assertNull("called back with null props", sync2_1.getProps());
// count3_1 = assertCallback(sync3_1, count3_1);
// assertNull("called back with null props", sync3_1.getProps());
// count3_2 = assertCallback(sync3_2, count3_2);
// assertNull("called back with null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, bundleT4, list);
}
}
public void testManagedServiceRegistrationMultipleTargets_11_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testManagedServiceRegistrationMultipleTargets_11_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
this.printoutPermissions();
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("*", "target", bundleT2, false);
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, null);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
sleep(3000);
if(conf.getBundleLocation().equals(bundleT1.getLocation())){
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props",
sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertEquals("conf.location must be dynamically set to location of T1.",
conf.getBundleLocation(),bundleT1.getLocation());
bundleT1.stop();
bundleT1.uninstall();
props.put("StringKey", "stringvalueNew");
trace("The configuration is being updated ");
conf.update(props);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with NON-null props",sync2_1.getProps());
bundleT2.stop();
bundleT2.uninstall();
}else if(conf.getBundleLocation().equals(bundleT2.getLocation())){
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with NON-null props",
sync2_1.getProps());
assertEquals("conf.location must be dynamically set to location of T2.",
conf.getBundleLocation(),bundleT2.getLocation());
trace("The bound bundleT2 is going to unregister MS.");
bundleT2.stop();
bundleT2.uninstall();
props.put("StringKey", "stringvalueNew");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props",sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
bundleT1.stop();
bundleT1.uninstall();
}else{
fail();
}
} finally {
cleanUpForCallbackTest(null, null, null, list);
}
}
public void testManagedServiceChangeLocation_12_1_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeLocation_12_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1,
bundleT2.getLocation());
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("conf.setBundleLocation() is being called.");
conf.setBundleLocation("?RegionA");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
// count1_2 = assertCallback(sync1_2, count1_2);
// assertNull("called back with null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, null, list);
}
}
public void testManagedServiceChangeLocation_12_1_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeLocation_12_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
assertEquals("conf.location must be set to \"?RegionA\".",
conf.getBundleLocation(), "?RegionA");
trace("conf.setBundleLocation() is being called.");
conf.setBundleLocation(bundleT2.getLocation());
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, null, list);
}
}
public void testManagedServiceChangeLocation_12_1_3() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeLocation_12_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
assertEquals("conf.location must be set to \"?RegionA\".",
conf.getBundleLocation(), "?RegionA");
trace("conf.setBundleLocation() is being called.");
conf.setBundleLocation("?RegionB");
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, null, list);
}
}
public void testManagedServiceChangeCP_12_2_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeCP_12_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
props.put("StringKey", "stringvalueNew");
trace("The configuration is being updated ");
conf.update(props);
//count1_1 = assertCallback(sync1_1, count1_1);
//assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceChangeCP_12_2_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeCP_12_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.setCPtoBundle("*", "target", bundleT1, false);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
props.put("StringKey", "stringvalueNew");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceStartCM_12_3_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceStartCM_12_3_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
Bundle cmBundle = this.stopCmBundle();
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
int count1_2 = 0;
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("CM is going to start");
startCmBundle(cmBundle);
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceStartCM_12_3_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceStartCM_12_3_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
// Dictionary props = new Hashtable();
// props.put("StringKey", "stringvalue");
// trace("The configuration is being updated ");
// conf.update(props);
Bundle cmBundle = this.stopCmBundle();
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
int count1_2 = 0;
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("CM is going to start");
startCmBundle(cmBundle);
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceStartCM_12_3_3() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceStartCM_12_3_3";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
Bundle cmBundle = this.stopCmBundle();
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
int count1_2 = 0;
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("CM is going to start");
startCmBundle(cmBundle);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceModifyPid_12_4_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
final String pid2 = Util.createPid("pid2");
List list = new ArrayList(5);
final String header = "testManagedServiceModifyPid_12_4_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
// modify PID
trace("modify PID from " + pid1 + " to " + pid2);
modifyPid(ManagedService.class.getName(), pid1, pid2);
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceModifyPid_12_4_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
final String pid2 = Util.createPid("pid2");
List list = new ArrayList(5);
final String header = "testManagedServiceModifyPid_12_4_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
// modify PID
trace("modify PID from " + pid2 + " to " + pid1);
modifyPid(ManagedService.class.getName(), pid2, pid1);
assertNoCallback(sync1_1, count1_1);
count1_1 = assertCallback(sync1_2, count1_2);
assertNotNull("called back with NON-null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
private void modifyPid(String clazz, String oldPid, String newPid) {
ServiceReference reference1 = this.getContext().getServiceReference(
ModifyPid.class.getName());
ModifyPid modifyPid = (ModifyPid) this.getContext().getService(
reference1);
ServiceReference[] references = null;
try {
references = this.getContext().getServiceReferences(clazz,
"(service.pid=" + oldPid + ")");
} catch (InvalidSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
trace("The pid of MS1-1 is being changed from " + oldPid + " to "
+ newPid);
modifyPid.changeMsPid(
(Long) (references[0].getProperty(Constants.SERVICE_ID)),
newPid);
}
public void testManagedServiceFactoryRegistration13_1_1() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryRegistration13_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
this.setCPtoBundle(null, null, bundleT1, false);
checkMsf_FirstRegThenCreateConf(bundleT1, fpid1, list,
bundleT1.getLocation(), true);
}
private void checkMsf_FirstRegThenCreateConf(Bundle bundleT1,
final String fpid1, List list, final String location,
boolean toBeCalledBack) throws BundleException, IOException {
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
int count1_2 = 0;
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, location);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
if (toBeCalledBack) {
count1_1 = assertCallback(sync1_1, count1_1);
props = sync1_1.getProps();
assertNotNull("null props must be called back", props);
assertNotNull("pid", props.get(Constants.SERVICE_PID));
assertFalse("pid",
props.get(Constants.SERVICE_PID).equals(fpid1));
assertEquals("fpid", fpid1,
props.get(ConfigurationAdmin.SERVICE_FACTORYPID));
assertEquals("value", "stringvalue", props.get("stringkey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 3", 3, props.size());
} else {
assertNoCallback(sync1_1, count1_1);
}
assertNoCallback(sync1_2, count1_2);
restartCM();
if (toBeCalledBack) {
count1_1 = assertCallback(sync1_1, count1_1);
props = sync1_1.getProps();
assertNotNull("null props must be called back", props);
assertNotNull("pid", props.get(Constants.SERVICE_PID));
assertFalse("pid",
props.get(Constants.SERVICE_PID).equals(fpid1));
assertEquals("fpid", fpid1,
props.get(ConfigurationAdmin.SERVICE_FACTORYPID));
assertEquals("value", "stringvalue", props.get("stringkey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 3", 3, props.size());
} else {
assertNoCallback(sync1_1, count1_1);
}
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryRegistration13_1_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryRegistration11_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
this.setCPtoBundle(null, null, bundleT1, false);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
bundleT1.getLocation());
int count1_1 = 0;
int count1_2 = 0;
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("Bundle is going to stop.");
bundleT1.stop();
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
props = sync1_1.getProps();
assertNotNull("null props must be called back", props);
assertNotNull("pid", props.get(Constants.SERVICE_PID));
assertFalse("pid", props.get(Constants.SERVICE_PID).equals(fpid1));
assertEquals("fpid", fpid1,
props.get(ConfigurationAdmin.SERVICE_FACTORYPID));
assertEquals("value", "stringvalue", props.get("stringkey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 3", 3, props.size());
trace("The configuration is being deleted. Wait for signal.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryRegistration13_2_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
/*
* A. Register in advance. Then create Configuration.
*/
final String header = "testManagedServiceFactoryRegistration13_2_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
this.setCPtoBundle("*", "target", bundleT1, false);
checkMsf_FirstRegThenCreateConf(bundleT1, fpid1, list,
bundleT2.getLocation(), false);
}
public void testManagedServiceFactoryRegistration13_2_5() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryRegistration13_2_5";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
this.setCPtoBundle(null, null, bundleT1, false);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
bundleT2.getLocation());
int count1_1 = 0;
int count1_2 = 0;
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1);
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("Bundle is going to stop.");
bundleT1.stop();
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
// count1_1 = assertCallback(sync1_1, count1_1);
// assertNotNull("called back with NON-null props",
// sync1_1.getProps());
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
// props = sync1_1.getProps();
// assertNotNull("null props must be called back", props);
// assertNotNull("pid", props.get(Constants.SERVICE_PID));
// assertFalse("pid",
// props.get(Constants.SERVICE_PID).equals(fpid1));
// assertEquals("fpid", fpid1,
// props.get(ConfigurationAdmin.SERVICE_FACTORYPID));
// assertEquals("value", "stringvalue", props.get("stringkey"));
// assertNull("bundleLocation must be not included",
// props.get("service.bundleLocation"));
// assertEquals("Size of props must be 3", 3, props.size());
trace("The configuration is being deleted. Wait for signal.");
conf.delete();
this.assertDeletedNoCallback(sync1_1, 0);
// count1_1 = this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_14_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
// final Bundle bundleT4 = getContext().installBundle(
// getWebServer() + "bundleT4.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_14_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?*", "target", bundleT2, false);
this.setCPtoBundle("?RegionA", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
this.assertDeletedCallback(sync2_1, 0);
this.assertDeletedCallback(sync3_1, 0);
this.assertDeletedCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_14_1_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
// final Bundle bundleT4 = getContext().installBundle(
// getWebServer() + "bundleT4.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_14_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle("?RegionB", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
this.assertDeletedNoCallback(sync2_1, 0);
this.assertDeletedNoCallback(sync3_1, 0);
this.assertDeletedNoCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_14_2_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_14_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?*", "target", bundleT2, false);
this.setCPtoBundle("?RegionA", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
this.startTargetBundle(bundleT1);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
this.assertDeletedCallback(sync2_1, 0);
this.assertDeletedCallback(sync3_1, 0);
this.assertDeletedCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_14_2_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_14_2_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle("?RegionB", "target", bundleT3, false);
// this.setCPtoBundle("?*", "target", bundleT2, false);
// this.setCPtoBundle("?RegionA", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
this.startTargetBundle(bundleT1);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
this.assertDeletedNoCallback(sync2_1, 0);
this.assertDeletedNoCallback(sync3_1, 0);
this.assertDeletedNoCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_15_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
//final Bundle bundleT3 = getContext().installBundle(
// getWebServer() + "bundleT3.jar");
// final Bundle bundleT4 = getContext().installBundle(
// getWebServer() + "bundleT4.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_15_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
//SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
//list.add(getContext().registerService(Synchronizer.class.getName(),
// sync3_1, propsForSyncF3_1));
//SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
//list.add(getContext().registerService(Synchronizer.class.getName(),
// sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("*", "target", bundleT2, false);
//this.setCPtoBundle("*", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
//int count3_1 = 0;
//int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
//this.startTargetBundle(bundleT3);
//assertNoCallback(sync3_1, count3_1);
//assertNoCallback(sync3_2, count3_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, null);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
//assertNoCallback(sync3_1, count3_1);
//assertNoCallback(sync3_2, count3_2);
// assertEquals(
// "The location of the conf must be dynamically bound to bundleT2",
// bundleT2.getLocation(), conf.getBundleLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
sleep(1000);
if(conf.getBundleLocation().equals(bundleT1.getLocation())){
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertEquals(
"The location of the conf must be dynamically bound to bundleT1",
bundleT1.getLocation(), conf.getBundleLocation());
trace("Bound bundleT1 is going to be stopped.");
bundleT1.stop();
bundleT1.uninstall();
sleep(1000);
assertEquals(
"The location of the conf must be dynamically bound to bundleT2",
bundleT2.getLocation(), conf.getBundleLocation());
count2_1 = assertCallback(sync2_1, count2_1);
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync2_1, 0);
bundleT2.stop();
bundleT2.uninstall();
}else if(conf.getBundleLocation().equals(bundleT2.getLocation())){
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
assertEquals(
"The location of the conf must be dynamically bound to bundleT2",
bundleT2.getLocation(), conf.getBundleLocation());
trace("Bound bundleT2 is going to be stopped.");
bundleT2.stop();
bundleT2.uninstall();
sleep(1000);
assertEquals(
"The location of the conf must be dynamically bound to bundleT1",
bundleT1.getLocation(), conf.getBundleLocation());
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
bundleT1.stop();
bundleT1.uninstall();
}else{
fail();
}
//trace("Wait for signal.");
//assertNoCallback(sync1_1, count1_1);
//assertNoCallback(sync1_2, count1_2);
//count2_1 = assertCallback(sync2_1, count2_1);
//assertNotNull("called back with Non-null props", sync2_1.getProps());
//assertNoCallback(sync3_1, count3_1);
//assertNoCallback(sync3_2, count3_2);
//trace("Bound bundleT2 is going to be stopped.");
//bundleT2.stop();
//assertEquals(
// "The location of the conf must be dynamically bound to bundleT3",
// bundleT3.getLocation(), conf.getBundleLocation());
// TODO confirm the behavior when the MSF gets unvisible. Will
// deleted(pid) be called back ?
//assertNoCallback(sync1_1, count1_1);
//assertNoCallback(sync1_2, count1_2);
//int countDeleted2_1 = this.assertDeletedCallback(sync2_1, 0);
//count3_1 = assertCallback(sync3_1, count3_1);
//assertNotNull("called back with Non-null props", sync3_1.getProps());
//count3_1 = assertCallback(sync3_2, count3_2);
//assertNotNull("called back with Non-null props", sync3_2.getProps());
//trace("conf is going to be deleted.");
//conf.delete();
//this.assertDeletedNoCallback(sync1_1, 0);
//this.assertDeletedNoCallback(sync1_2, 0);
//this.assertDeletedNoCallback(sync2_1, countDeleted2_1);
//this.assertDeletedCallback(sync3_1, 0);
//this.assertDeletedCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(null, null, null, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_15_1_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_15_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
int count1_1 = 0;
int count1_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, null);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertEquals(
"The location of the conf must be dynamically bound to bundleT1",
bundleT1.getLocation(), conf.getBundleLocation());
trace("Bound bundleT1 is going to be stopped.");
bundleT1.stop();
bundleT1.uninstall();
sleep(1000);
assertNull(
"The location of the conf must be dynamically unbound to null.",
conf.getBundleLocation());
} finally {
cleanUpForCallbackTest(null, null, null, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_15_2_1()
throws Exception {
// TODO impl
}
public void testManagedServiceFactoryRegistrationMultipleTargets_15_3_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
// final Bundle bundleT4 = getContext().installBundle(
// getWebServer() + "bundleT4.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_15_3_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle(bundleT2.getLocation(), "target", bundleT2,
false);
this.setCPtoBundle("?", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, "?");
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
this.startTargetBundle(bundleT1);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleCF_16_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleCF_16_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle(null, null, bundleT3, false);
// this.setCPtoBundle(null, null, bundleT2, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configurations are being created");
Configuration conf1 = cm.createFactoryConfiguration(fpid1,
"?RegionA");
Configuration conf2 = cm.createFactoryConfiguration(fpid1, "?");
Configuration conf3 = cm.createFactoryConfiguration(fpid1,
bundleT3.getLocation());
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf1 is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf1.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf2 is being updated ");
conf2.update(props);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
// count2_1 = assertCallback(sync2_1, count2_1);
// assertNotNull("called back with Non-null props",
// sync2_1.getProps());
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf3 is being updated ");
conf3.update(props);
trace("Wait for signal.");
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleCF_16_1_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleCF_16_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("?*", "target", bundleT1, false);
this.setCPtoBundle("?", "target", bundleT2, false);
this.setCPtoBundle(null, null, bundleT3, false);
// this.setCPtoBundle(null, null, bundleT2, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configurations are being created");
Configuration conf1 = cm.createFactoryConfiguration(fpid1,
"?RegionA");
Configuration conf2 = cm.createFactoryConfiguration(fpid1, "?");
Configuration conf3 = cm.createFactoryConfiguration(fpid1,
bundleT3.getLocation());
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf1 is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf1.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf2 is being updated ");
conf2.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
// assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf3 is being updated ");
conf3.update(props);
trace("Wait for signal.");
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryCmRestart18_3_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryCmRestart18_3_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
bundleT1.getLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("CM Bundle is going to start.");
Bundle cmBundle = stopCmBundle();
this.setCPtoBundle("*", "target", bundleT1, false);
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
int count1_1 = 0;
int count1_2 = 0;
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("CM Bundle is going to start.");
this.startTargetBundle(cmBundle);
assignCm();
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryModifyPid18_4_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
final String fpid2 = Util.createPid("factoryPid2");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryModifyPid18_4_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
this.setCPtoBundle("*", "target", bundleT1, false);
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
int count1_1 = 0;
int count1_2 = 0;
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, "?");
// Configuration conf =
// cm.createFactoryConfiguration(fpid1,bundleT1.getLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
// modify PID
modifyPid(ManagedServiceFactory.class.getName(), fpid2, fpid1);
// ServiceReference[] references = this.getContext()
// .getServiceReferences(
// ManagedServiceFactory.class.getName(), null);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
count1_2 = assertCallback(sync1_2, count1_2);
assertNotNull("called back with NON-null props", sync1_2.getProps());
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryDeletion18_5_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryDeletion18_5_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
this.setCPtoBundle("*", "target", bundleT1, false);
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
int count1_1 = 0;
int count1_2 = 0;
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being deleted. Wait for signal.");
conf.delete();
int countDeteted1_1 = this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
trace("The configuration is being created");
Configuration conf2 = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("The configuration is being updated ");
conf2.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
trace("Change permission of bundleT1 ");
this.setCPtoBundle(null, null, bundleT1, false);
trace("The configuration is being deleted. Wait for signal.");
conf2.delete();
this.assertDeletedNoCallback(sync1_1, countDeteted1_1);
this.assertDeletedNoCallback(sync1_2, 0);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
}
| org.osgi.test.cases.cm/src/org/osgi/test/cases/cm/junit/CMControl.java | /*
* Copyright (c) OSGi Alliance (2000, 2012). All Rights Reserved.
*
* Implementation of certain elements of the OSGi
* Specification may be subject to third party intellectual property
* rights, including without limitation, patent rights (such a third party may
* or may not be a member of the OSGi Alliance). The OSGi Alliance is not responsible and shall not be
* held responsible in any manner for identifying or failing to identify any or
* all such third party intellectual property rights.
*
* This document and the information contained herein are provided on an "AS
* IS" basis and THE OSGI ALLIANCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL
* NOT INFRINGE ANY RIGHTS AND ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE OSGI ALLIANCE BE LIABLE FOR ANY
* LOSS OF PROFITS, LOSS OF BUSINESS, LOSS OF USE OF DATA, INTERRUPTION OF
* BUSINESS, OR FOR DIRECT, INDIRECT, SPECIAL OR EXEMPLARY, INCIDENTIAL,
* PUNITIVE OR CONSEQUENTIAL DAMAGES OF ANY KIND IN CONNECTION WITH THIS
* DOCUMENT OR THE INFORMATION CONTAINED HEREIN, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH LOSS OR DAMAGE.
*
* All Company, brand and product names may be trademarks that are the sole
* property of their respective owners. All rights reserved.
*/
package org.osgi.test.cases.cm.junit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.PropertyPermission;
import java.util.Set;
import junit.framework.AssertionFailedError;
import org.osgi.framework.AdminPermission;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.PackagePermission;
import org.osgi.framework.ServicePermission;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ConfigurationEvent;
import org.osgi.service.cm.ConfigurationListener;
import org.osgi.service.cm.ConfigurationPermission;
import org.osgi.service.cm.ConfigurationPlugin;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.cm.ManagedServiceFactory;
import org.osgi.service.cm.SynchronousConfigurationListener;
import org.osgi.service.permissionadmin.PermissionAdmin;
import org.osgi.service.permissionadmin.PermissionInfo;
import org.osgi.test.cases.cm.common.ConfigurationListenerImpl;
import org.osgi.test.cases.cm.common.SynchronizerImpl;
import org.osgi.test.cases.cm.shared.ModifyPid;
import org.osgi.test.cases.cm.shared.Synchronizer;
import org.osgi.test.cases.cm.shared.Util;
import org.osgi.test.support.compatibility.DefaultTestBundleControl;
import org.osgi.test.support.compatibility.Semaphore;
import org.osgi.test.support.sleep.Sleep;
/**
* @author Ikuo YAMASAKI, NTT Corporation, added many tests.
* @author Carsten Ziegeler, Adobe, added ConfigAdmin 1.5 tests
*/
public class CMControl extends DefaultTestBundleControl {
private ConfigurationAdmin cm;
private PermissionAdmin permAdmin;
private static final long SIGNAL_WAITING_TIME = Long.getLong("org.osgi.test.cases.cm.signal_waiting_time", 4000).longValue();
private List list;
private boolean permissionFlag;
private Bundle setAllPermissionBundle;
private String thisLocation = null;
private Bundle thisBundle = null;
private Set existingConfigs;
private static final String SP = ServicePermission.class.getName();
private static final String PP = PackagePermission.class.getName();
private static final String AP = AdminPermission.class.getName();
private static final String CP = ConfigurationPermission.class.getName();
private static final Dictionary propsForSync1;
static {
propsForSync1 = new Hashtable();
propsForSync1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync1");
}
private static final Dictionary propsForSync2;
static {
propsForSync2 = new Hashtable();
propsForSync2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync2");
}
private static final Dictionary propsForSync1_1;
static {
propsForSync1_1 = new Hashtable();
propsForSync1_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync1-1");
}
private static final Dictionary propsForSync1_2;
static {
propsForSync1_2 = new Hashtable();
propsForSync1_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync1-2");
}
private static final Dictionary propsForSync2_1;
static {
propsForSync2_1 = new Hashtable();
propsForSync2_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync2-1");
}
private static final Dictionary propsForSync3_1;
static {
propsForSync3_1 = new Hashtable();
propsForSync3_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync3-1");
}
private static final Dictionary propsForSync3_2;
static {
propsForSync3_2 = new Hashtable();
propsForSync3_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync3-2");
}
private static final Dictionary propsForSync4_1;
static {
propsForSync4_1 = new Hashtable();
propsForSync4_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync4-1");
}
private static final Dictionary propsForSync4_2;
static {
propsForSync4_2 = new Hashtable();
propsForSync4_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"sync4-2");
}
private static final Dictionary propsForSyncF1_1;
static {
propsForSyncF1_1 = new Hashtable();
propsForSyncF1_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF1-1");
}
private static final Dictionary propsForSyncF1_2;
static {
propsForSyncF1_2 = new Hashtable();
propsForSyncF1_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF1-2");
}
private static final Dictionary propsForSyncF2_1;
static {
propsForSyncF2_1 = new Hashtable();
propsForSyncF2_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF2-1");
}
private static final Dictionary propsForSyncF3_1;
static {
propsForSyncF3_1 = new Hashtable();
propsForSyncF3_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF3-1");
}
private static final Dictionary propsForSyncF3_2;
static {
propsForSyncF3_2 = new Hashtable();
propsForSyncF3_2.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncF3-2");
}
private static final Dictionary propsForSyncT5_1;
static {
propsForSyncT5_1 = new Hashtable();
propsForSyncT5_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncT5-1");
}
private static final Dictionary propsForSyncT6_1;
static {
propsForSyncT6_1 = new Hashtable();
propsForSyncT6_1.put(
org.osgi.test.cases.cm.shared.Constants.SERVICEPROP_KEY_SYNCID,
"syncT6-1");
}
private static final String neverlandLocation = "http://neverneverland/";
protected void setUp() throws Exception {
// printoutBundleList();
assignCm();
// populate the created configurations so that
// listConfigurations can return these configurations
list = new ArrayList(5);
if (System.getSecurityManager() != null) {
permAdmin = (PermissionAdmin) getService(PermissionAdmin.class);
setAllPermissionBundle = getContext().installBundle(
getWebServer() + "setallpermission.jar");
thisBundle = getContext().getBundle();
thisLocation = thisBundle.getLocation();
} else {
permissionFlag = true;
}
// existing configurations
Configuration[] configs = cm.listConfigurations(null);
existingConfigs = new HashSet();
if (configs != null) {
for (int i = 0; i < configs.length; i++) {
Configuration config = configs[i];
// log("setUp() -- Register pre-existing config " + config.getPid());
existingConfigs.add(config.getPid());
}
}
}
protected void tearDown() throws Exception {
resetPermissions();
cleanCM(existingConfigs);
if (this.setAllPermissionBundle != null) {
this.setAllPermissionBundle.uninstall();
this.setAllPermissionBundle = null;
}
if (permAdmin != null)
ungetService(permAdmin);
list = null;
unregisterAllServices();
ungetService(cm);
System.out.println("tearDown()");
// this.printoutBundleList();
}
private void resetPermissions() throws BundleException {
if (permAdmin == null)
return;
try {
if (this.setAllPermissionBundle == null)
this.setAllPermissionBundle = getContext().installBundle(
getWebServer() + "setallpermission.jar");
this.setAllPermissionBundle.start();
this.setAllPermissionBundle.stop();
} catch (BundleException e) {
Exception ise = new IllegalStateException(
"fail to install or start setallpermission bundle.");
ise.initCause(e);
throw e;
}
this.printoutPermissions();
}
private void printoutPermissions() {
if (permAdmin == null)
return;
String[] locations = this.permAdmin.getLocations();
if (locations != null)
for (int i = 0; i < locations.length; i++) {
System.out.println("locations[" + i + "]=" + locations[i]);
PermissionInfo[] pInfos = this.permAdmin
.getPermissions(locations[i]);
for (int j = 0; j < pInfos.length; j++) {
System.out.println("\t" + pInfos[j]);
}
}
PermissionInfo[] pInfos = this.permAdmin.getDefaultPermissions();
if (pInfos == null)
System.out.println("default permission=null");
else {
System.out.println("default permission=");
for (int j = 0; j < pInfos.length; j++) {
System.out.println("\t" + pInfos[j]);
}
}
}
private void printoutBundleList() {
Bundle[] bundles = this.getContext().getBundles();
for (int i = 0; i < bundles.length; i++) {
System.out.println("bundles[" + i + "]="
+ bundles[i].getSymbolicName() + "["
+ bundles[i].getState() + "]");
// if (bundles[i].getState() != Bundle.ACTIVE)
// System.exit(0);
}
}
private void setBundlePermission(Bundle b, List list) {
if (permAdmin == null)
return;
PermissionInfo[] pis = new PermissionInfo[list.size()];
pis = (PermissionInfo[]) list.toArray(pis);
permAdmin.setPermissions(b.getLocation(), pis);
this.printoutPermissions();
}
private List getBundlePermission(Bundle b) {
if (permAdmin == null) return null;
PermissionInfo[] pis = permAdmin.getPermissions(b.getLocation());
return Arrays.asList(pis);
}
private void add(List permissionsInfos, String clazz, String name,
String actions) {
permissionsInfos.add(new PermissionInfo(clazz, name, actions));
}
/** *** Test methods **** */
/**
* Test that the methods throws IllegalStateException when operating on a
* deleted Configuration
*
* @spec Configuration.delete()
* @spec Configuration.getBundleLocation()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getPid()
* @spec Configuration.getProperties()
* @spec Configuration.setBundleLocation(String)
*/
public void testDeletedConfiguration() throws Exception {
String pid = Util.createPid();
Configuration conf = null;
/* Get a brand new configuration and delete it. */
conf = cm.getConfiguration(pid);
conf.delete();
/*
* A list of all methodcalls that should be made to the deleted
* Configuration object
*/
MethodCall[] methods = {
new MethodCall(Configuration.class, "delete"),
new MethodCall(Configuration.class, "getBundleLocation"),
new MethodCall(Configuration.class, "getFactoryPid"),
new MethodCall(Configuration.class, "getPid"),
new MethodCall(Configuration.class, "getProperties"),
new MethodCall(Configuration.class, "getChangeCount"),
new MethodCall(Configuration.class, "setBundleLocation",
String.class, "somelocation"),
new MethodCall(Configuration.class, "update"),
new MethodCall(Configuration.class, "update", Dictionary.class,
new Hashtable()) };
/* Make all the methodcalls in the list */
for (int i = 0; i < methods.length; i++) {
try {
/* Call the method on the Configuration object */
methods[i].invoke(conf);
/*
* In this case it should always throw an IllegalStateException
* so if we end up here, somethings wrong
*/
failException(methods[i].getName(), IllegalStateException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(methods[i].getName(),
IllegalStateException.class, e);
}
}
}
/**
* TODO comments
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec ConfigurationAdmin.getConfiguration(String,String)
* @spec Configuration.getBundleLocation()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getPid()
* @spec Configuration.getProperties()
* @spec Configuration.setBundleLocation(String)
*
* @throws Exception
*/
public void testGetConfiguration() throws Exception {
this.setInappropriatePermission();
String pid = Util.createPid();
String thisLocation = getLocation();
Configuration conf = null;
/* Get a brand new configuration */
conf = cm.getConfiguration(pid);
checkConfiguration(conf, "A new Configuration object", pid,
thisLocation);
/* Get location of the configuration */
/* must fail because of inappropriate Permission. */
String message = "try to get location without appropriate ConfigurationPermission.";
try {
conf.getBundleLocation();
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null) failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null) fail("Security is not enabled", e);
}
/* Get the configuration again (should be exactly the same) */
conf = cm.getConfiguration(pid);
checkConfiguration(conf, "The same Configuration object", pid,
thisLocation);
/*
* Change the location of the bundle and then get the Configuration
* again. The location should not have been touched.
*/
/* must fail because of inappropriate Permission. */
message = "try to set location without appropriate ConfigurationPermission.";
try {
conf.setBundleLocation(neverlandLocation);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
conf.setBundleLocation(neverlandLocation);
conf = cm.getConfiguration(pid);
assertEquals("Location Neverland", neverlandLocation,
this.getBundleLocationForCompare(conf));
this.setInappropriatePermission();
/* must fail because of inappropriate Permission. */
message = "try to get configuration whose location is different from the caller bundle without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
/* Clean up */
conf.delete();
}
/**
* TODO comments
*
* @spec ConfigurationAdmin.getConfiguration(String,String)
* @spec Configuration.getBundleLocation()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.getProperties()
*
* @throws Exception
*/
public void testGetConfigurationWithLocation() throws Exception {
final String pid1 = Util.createPid("1");
final String pid2 = Util.createPid("2");
final String pid3 = Util.createPid("3");
// final String thisLocation = getLocation();
Configuration conf = null;
this.printoutPermissions();
this.setInappropriatePermission();
/*
* Without appropriate ConfigurationPermission, Get a brand new
* configuration.
*/
String message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid1, thisLocation);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
fail("Throwable must not be thrown for Configuration#getBundleLocation()",
e);
}
/*
* Without appropriate ConfigurationPermission, Get an existing
* configuration with thisLocation, but specify the location (which
* should then be ignored).
*/
// TODO Change the explanation
message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid1, neverlandLocation);
// checkConfiguration(conf, "The same Configuration object",
// pid1,thisLocation);
fail("SecurityException must be thrown because cm must check the set location.");
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// fail("Throwable must not be thrown because the configuring bundle has implicit CP for thisLocation",e);
}
conf.delete();
this.setInappropriatePermission();
/*
* Without appropriate ConfigurationPermission, Get a brand new
* configuration with a specified location
*/
message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid2, neverlandLocation);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
/* Get a brand new configuration with a specified location */
conf = cm.getConfiguration(pid2, neverlandLocation);
checkConfiguration(conf, "A new Configuration object", pid2,
neverlandLocation);
conf.delete();
this.setInappropriatePermission();
/*
* Without appropriate ConfigurationPermission, Get a brand new
* configuration with no location
*/
message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(pid3, null);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
/* Get a brand new configuration with no location */
conf = cm.getConfiguration(pid3, null);
checkConfiguration(conf, "A new Configuration object", pid3, null);
conf.delete();
}
/**
* TODO comments
*
* @spec ConfigurationAdmin.getConfiguration(String,String)
* @spec Configuration.getBundleLocation()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.getProperties()
*
* @throws Exception
*/
public void testConfigurationWithNullLocation() throws Exception {
final String bundlePid = Util.createPid("bundle1Pid");
final String thisLocation = getLocation();
Configuration conf = null;
this.setInappropriatePermission();
/*
* Without appropriate ConfigurationPermission, Get a brand new
* configuration with no location
*/
String message = "try to get configuration without appropriate ConfigurationPermission.";
try {
conf = cm.getConfiguration(bundlePid, null);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
/* Get a brand new configuration with no location */
conf = cm.getConfiguration(bundlePid, null);
checkConfiguration(conf, "A new Configuration object", bundlePid, null);
Dictionary props = new Hashtable();
props.put("StringKey", getName());
conf.update(props);
/*
* Get existing Configuration with neverland location, which should be
* ignored
*/
Configuration conf3 = cm.getConfiguration(bundlePid, neverlandLocation);
assertEquals("Pid", bundlePid, conf3.getPid());
assertNull("FactoryPid", conf3.getFactoryPid());
assertNull("Location", this.getBundleLocationForCompare(conf3));
assertEquals("The same Confiuration props", getName(), conf3
.getProperties().get("StringKey"));
System.out.println("###########################"
+ conf3.getBundleLocation());
// System.out.println("###########################"+cm.getConfiguration(bundlePid).getBundleLocation());
this.setInappropriatePermission();
/* Get location of the configuration with null location */
/* must fail because of inappropriate Permission. */
message = "try to get location without appropriate ConfigurationPermission.";
try {
conf.getBundleLocation();
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
message = "try to get configuration with null location without appropriate ConfigurationPermission.";
/*
* try { Configuration conf4 = cm.getConfiguration(bundlePid);
*
* A SecurityException should have been thrown if security is enabled
*
* if (System.getSecurityManager() != null) failException(message,
* SecurityException.class); } catch (AssertionFailedError e) { throw e;
* } catch (Throwable e) { Check that we got the correct exception
* assertException(message, SecurityException.class, e);
*
* A SecurityException should not have been thrown if security is not
* enabled
*
* if (System.getSecurityManager() == null)
* fail("Security is not enabled", e); }
*/
Configuration conf4 = cm.getConfiguration(bundlePid);
/* location MUST be changed to the callers bundle's location. */
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf4));
/* In order to get Location, appropriate permission is required. */
this.setAppropriatePermission();
cm.getConfiguration(bundlePid).setBundleLocation(null);
Configuration conf5 = cm.getConfiguration(bundlePid);
/* location MUST be changed to the callers bundle's location. */
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf5));
// this.setAppropriatePermission();
// conf3 = cm.getConfiguration(pid3);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf3));
this.setInappropriatePermission();
/* Set location of the configuration to null location */
/* must fail because of inappropriate Permission. */
message = "try to set location to null without appropriate ConfigurationPermission.";
try {
conf.setBundleLocation(null);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
this.setAppropriatePermission();
conf.setBundleLocation(null);
this.setInappropriatePermission();
/* Set location of the configuration with null location to others */
/* must fail because of inappropriate Permission. */
message = "try to set location to null without appropriate ConfigurationPermission.";
try {
conf.setBundleLocation(thisLocation);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
try {
conf.setBundleLocation(neverlandLocation);
/*
* A SecurityException should have been thrown if security is
* enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if security is
* not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
conf.delete();
}
/**
* Test the change counter.
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testChangeCount() throws Exception {
trace("Testing change count...");
// create config with pid
trace("Create test configuration");
final String pid = "test_ca_counter_" + ConfigurationListenerImpl.LISTENER_PID_SUFFIX;
final Configuration config = this.cm.getConfiguration(pid);
final long startCount = config.getChangeCount();
// register sync and async listener for change updates
trace("Create and register configuration listeners");
// list to check whether the sync listener is called
final List events = new ArrayList();
final SynchronousConfigurationListener scl = new SynchronousConfigurationListener() {
// the sync listener is called during the update method and the
// change count should of course already be updated.
public void configurationEvent(final ConfigurationEvent event) {
if (event.getPid() != null
&& event.getPid().endsWith(ConfigurationListenerImpl.LISTENER_PID_SUFFIX)
&& event.getFactoryPid() == null) {
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
assertTrue("Expect second change count to be higher than " + startCount + " : " + config.getChangeCount(),
config.getChangeCount() > startCount);
events.add(event);
}
}
};
ConfigurationListenerImpl cl = null;
final SynchronizerImpl synchronizer = new SynchronizerImpl();
this.registerService(SynchronousConfigurationListener.class.getName(), scl, null);
try {
cl = createConfigurationListener(synchronizer);
// update config with properties
config.update(new Hashtable(){{put("x", "x");}});
assertTrue("Sync listener not called.", events.size() == 1);
assertTrue("Expect second change count to be higher than " + startCount + " : " + config.getChangeCount(),
config.getChangeCount() > startCount);
trace("Wait until the ConfigurationListener has gotten the update");
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
trace("Checking configuration event");
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType());
// reget configuration and check count
trace("Checking regetting configuration");
final Configuration configNew = this.cm.getConfiguration(pid);
assertEquals("Configuration change count shouldn't have changed", config.getChangeCount(), configNew.getChangeCount());
assertTrue("Expect second change count to be higher than " + startCount + " : " + configNew.getChangeCount(),
configNew.getChangeCount() > startCount);
trace("Testing change count...finished");
} finally {
// clean up
if ( cl != null ) {
removeConfigurationListener(cl);
}
this.unregisterService(scl);
config.delete();
}
}
/**
* Test the change counter for factory configuration
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testChangeCountFactory() throws Exception {
trace("Testing change count factory...");
// create config with pid
trace("Create test configuration");
final String factoryPid = "test_ca_counter_factory_" + ConfigurationListenerImpl.LISTENER_PID_SUFFIX;
final Configuration config = this.cm.createFactoryConfiguration(factoryPid);
final String pid = config.getPid();
final long startCount = config.getChangeCount();
// register sync and async listener for change updates
trace("Create and register configuration listeners");
// list to check whether the sync listener is called
final List events = new ArrayList();
final SynchronousConfigurationListener scl = new SynchronousConfigurationListener() {
// the sync listener is called during the update method and the
// change count should of course already be updated.
public void configurationEvent(final ConfigurationEvent event) {
if (event.getPid() != null
&& event.getFactoryPid().endsWith(ConfigurationListenerImpl.LISTENER_PID_SUFFIX)) {
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
assertTrue("Expect second change count to be higher than " + startCount + " : " + config.getChangeCount(),
config.getChangeCount() > startCount);
events.add(event);
}
}
};
ConfigurationListenerImpl cl = null;
final SynchronizerImpl synchronizer = new SynchronizerImpl();
this.registerService(SynchronousConfigurationListener.class.getName(), scl, null);
try {
cl = createConfigurationListener(synchronizer);
// update config with properties
config.update(new Hashtable(){{put("x", "x");}});
assertTrue("Sync listener not called.", events.size() == 1);
assertTrue("Expect second change count to be higher than " + startCount + " : " + config.getChangeCount(),
config.getChangeCount() > startCount);
trace("Wait until the ConfigurationListener has gotten the update");
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
trace("Checking configuration event");
assertEquals("Config event factory pid match", factoryPid, cl.getFactoryPid());
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType());
// reget configuration and check count
trace("Checking regetting configuration");
final Configuration[] cfs = cm.listConfigurations( "(" + ConfigurationAdmin.SERVICE_FACTORYPID + "="
+ factoryPid + ")" );
final Configuration configNew = cfs[0];
assertEquals("Configuration change count shouldn't have changed", config.getChangeCount(), configNew.getChangeCount());
assertTrue("Expect second change count to be higher than " + startCount + " : " + configNew.getChangeCount(),
configNew.getChangeCount() > startCount);
trace("Testing change count...finished");
} finally {
// clean up
if ( cl != null ) {
removeConfigurationListener(cl);
}
this.unregisterService(scl);
config.delete();
}
}
/**
* Test sync listener.
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testSyncListener() throws Exception {
trace("Testing sync listener...");
trace("Create and register sync configuration listeners");
// List of events
final List events = new ArrayList();
// Thread check
final Thread callerThread = Thread.currentThread();
final SynchronousConfigurationListener scl = new SynchronousConfigurationListener() {
// the sync listener is called during the update method and the
// change count should of course already be updated.
public void configurationEvent(final ConfigurationEvent event) {
if (event.getPid() != null
&& event.getPid().endsWith(ConfigurationListenerImpl.LISTENER_PID_SUFFIX)
&& event.getFactoryPid() == null) {
// check thread
if ( Thread.currentThread() != callerThread ) {
fail("Method is not called in sync.");
}
events.add(event);
}
}
};
this.registerService(SynchronousConfigurationListener.class.getName(), scl, null);
Configuration config = null;
try {
// create config with pid
trace("Create test configuration");
final String pid = "test_sync_config_" + ConfigurationListenerImpl.LISTENER_PID_SUFFIX;
config = this.cm.getConfiguration(pid);
config.update(new Hashtable(){{put("y", "y");}});
assertEquals("No event received: " + events, 1, events.size());
ConfigurationEvent event = (ConfigurationEvent)events.get(0);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
// update config
config.update(new Hashtable(){{put("x", "x");}});
assertEquals("No event received", 2, events.size());
event = (ConfigurationEvent)events.get(1);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
// update location
config.setBundleLocation("location");
assertEquals("No event received", 3, events.size());
event = (ConfigurationEvent)events.get(2);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_LOCATION_CHANGED, event.getType());
// delete config
config.delete();
config = null;
assertEquals("No event received", 4, events.size());
event = (ConfigurationEvent)events.get(3);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, event.getType());
} finally {
this.unregisterService(scl);
if ( config != null ) {
config.delete();
}
}
trace("Testing sync listener...finished");
}
/**
* Test sync listener for factory config.
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testSyncListenerFactory() throws Exception {
trace("Testing sync listener...");
trace("Create and register sync configuration listeners");
// List of events
final List events = new ArrayList();
// Thread check
final Thread callerThread = Thread.currentThread();
final SynchronousConfigurationListener scl = new SynchronousConfigurationListener() {
// the sync listener is called during the update method and the
// change count should of course already be updated.
public void configurationEvent(final ConfigurationEvent event) {
if (event.getPid() != null
&& event.getFactoryPid().endsWith(ConfigurationListenerImpl.LISTENER_PID_SUFFIX)) {
// check thread
if ( Thread.currentThread() != callerThread ) {
fail("Method is not called in sync.");
}
events.add(event);
}
}
};
this.registerService(SynchronousConfigurationListener.class.getName(), scl, null);
Configuration config = null;
try {
// create config with pid
trace("Create test configuration");
final String factoryPid = "test_sync_config_factory_" + ConfigurationListenerImpl.LISTENER_PID_SUFFIX;
config = this.cm.createFactoryConfiguration(factoryPid);
final String pid = config.getPid();
config.update(new Hashtable(){{put("y", "y");}});
assertEquals("No event received: " + events, 1, events.size());
ConfigurationEvent event = (ConfigurationEvent)events.get(0);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
// update config
config.update(new Hashtable(){{put("x", "x");}});
assertEquals("No event received", 2, events.size());
event = (ConfigurationEvent)events.get(1);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, event.getType());
// update location
config.setBundleLocation("location");
assertEquals("No event received", 3, events.size());
event = (ConfigurationEvent)events.get(2);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_LOCATION_CHANGED, event.getType());
// delete config
config.delete();
config = null;
assertEquals("No event received", 4, events.size());
event = (ConfigurationEvent)events.get(3);
assertEquals("Config event pid match", pid, event.getPid());
assertEquals("Config event factory pid match", factoryPid, event.getFactoryPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, event.getType());
} finally {
this.unregisterService(scl);
if ( config != null ) {
config.delete();
}
}
trace("Testing sync listener...finished");
}
/**
* Test targeted pids
* Create configs for the same pid, each new config is either more "specific" than
* the previous one or "invalid"
* Check if the new config is either bound or ignored
* Then delete configs in reverse order and check if either nothing is happening
* ("invalid" configs) or rebound to a previous config happens.
*
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testTargetedPid() throws Exception {
trace("Testing targeted pids...");
final Bundle bundleT5 = getContext().installBundle(
getWebServer() + "bundleT5.jar");
final Bundle bundleT6 = getContext().installBundle(
getWebServer() + "bundleT6.jar");
final String pidBase = Util.createPid("pid_targeted1");
// create a list of configurations
// the first char is a "bitset":
// if bit 1 is set, T5 should get the config
// if bit 2 is set, T6 should get the config
// so: 0 : no delivery, 1 : T5, 2: T6, 3: T5 + T6
final String[] pids = new String[] {
"3" + pidBase,
"1" + pidBase + "|" + bundleT5.getSymbolicName(),
"2" + pidBase + "|" + bundleT6.getSymbolicName(),
"0" + pidBase + "|Not" + bundleT5.getSymbolicName(),
"1" + pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString(),
"2" + pidBase + "|" + bundleT6.getSymbolicName() + "|" + bundleT6.getHeaders().get(Constants.BUNDLE_VERSION).toString(),
"0" + pidBase + "|" + bundleT5.getSymbolicName() + "|555.555.555.Not",
"0" + pidBase + "|" + bundleT6.getSymbolicName() + "|555.555.555.Not",
"1" + pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT5.getLocation(),
"2" + pidBase + "|" + bundleT6.getSymbolicName() + "|" + bundleT6.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT6.getLocation(),
"0" + pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT5.getLocation() + "Not",
"0" + pidBase + "|" + bundleT6.getSymbolicName() + "|" + bundleT6.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT6.getLocation() + "Not"
};
final List list = new ArrayList(5);
final List configs = new ArrayList();
try {
final SynchronizerImpl sync1_1 = new SynchronizerImpl("T5-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncT5_1));
final SynchronizerImpl sync2_1 = new SynchronizerImpl("T6-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncT6_1));
this.startTargetBundle(bundleT5);
this.setCPtoBundle("*", ConfigurationPermission.TARGET, bundleT5, false);
this.startTargetBundle(bundleT6);
this.setCPtoBundle("*", ConfigurationPermission.TARGET, bundleT6, false);
trace("Wait for signal.");
int count1_1 = 0, count2_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
// let's create some configurations
String previousKeyT5 = null, previousKeyT6 = null;
for(int i=0; i<pids.length; i++) {
// key contains marker at char 0 + pid
final String key = pids[i];
final String pid = key.substring(1);
trace("Creating config " + pid);
final Configuration c = this.cm.getConfiguration(pid, "?*");
configs.add(c);
final String propPreviousKeyT5 = previousKeyT5;
final String propPreviousKeyT6 = previousKeyT6;
c.update(new Hashtable(){
{
put("test", key);
if ( propPreviousKeyT5 != null ) {
put("previousT5", propPreviousKeyT5);
}
if ( propPreviousKeyT6 != null ) {
put("previousT6", propPreviousKeyT6);
}
}
});
// check T5
final char deliveryMarker = key.charAt(0);
if ( deliveryMarker == '0' || deliveryMarker == '2') {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
assertEquals("Pid is wrong", key, sync1_1.getProps().get("test"));
previousKeyT5 = key;
}
// check T6
if ( deliveryMarker == '0' || deliveryMarker == '1') {
assertNoCallback(sync2_1, count2_1);
} else {
count2_1 = assertCallback(sync2_1, count2_1);
assertEquals("Pid is wrong", key, sync2_1.getProps().get("test"));
previousKeyT6 = key;
}
}
// we now delete the configuration in reverse order
while ( configs.size() > 0 ) {
final Configuration c = (Configuration) configs.remove(configs.size() - 1);
final String key = (String) c.getProperties().get("test");
previousKeyT5 = (String) c.getProperties().get("previousT5");
previousKeyT6 = (String) c.getProperties().get("previousT6");
c.delete();
// check T5
final char deliveryMarker = key.charAt(0);
if ( deliveryMarker == '0' || deliveryMarker == '2') {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
if ( configs.size() == 0 ) {
// removed last config, so this is a delete
assertNull(sync1_1.getProps());
} else {
// this is an update = downgrade to a previous config
assertNotNull(sync1_1.getProps());
final String newPid = (String) sync1_1.getProps().get("test");
assertEquals("Pid is wrong", previousKeyT5, newPid);
}
}
// check T6
if ( deliveryMarker == '0' || deliveryMarker == '1') {
assertNoCallback(sync2_1, count2_1);
} else {
count2_1 = assertCallback(sync2_1, count2_1);
if ( configs.size() == 0 ) {
// removed last config, so this is a delete
assertNull(sync2_1.getProps());
} else {
// this is an update = downgrade to a previous config
assertNotNull(sync2_1.getProps());
final String newPid = (String) sync2_1.getProps().get("test");
assertEquals("Pid is wrong", previousKeyT6, newPid);
}
}
}
} finally {
cleanUpForCallbackTest(bundleT5, bundleT6, null, null, list);
Iterator i = configs.iterator();
while ( i.hasNext() ) {
final Configuration c = (Configuration) i.next();
c.delete();
}
}
trace("Testing targeted pids...finished");
}
/**
* Test targeted factory pids
*
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testTargetedFactoryPid() throws Exception {
trace("Testing targeted factory pids...");
final Bundle bundleT5 = getContext().installBundle(
getWebServer() + "bundleT5.jar");
final String pidBase = Util.createPid("pid_targeted3");
final String[] pids = new String[] {
pidBase,
pidBase + "|" + bundleT5.getSymbolicName(),
pidBase + "|Not" + bundleT5.getSymbolicName(),
pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString(),
pidBase + "|" + bundleT5.getSymbolicName() + "|555.555.555.Not",
pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT5.getLocation(),
pidBase + "|" + bundleT5.getSymbolicName() + "|" + bundleT5.getHeaders().get(Constants.BUNDLE_VERSION).toString() + "|" + bundleT5.getLocation() + "Not"
};
final List list = new ArrayList(5);
final List configs = new ArrayList();
try {
final SynchronizerImpl sync1_1 = new SynchronizerImpl("T5-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncT5_1));
this.startTargetBundle(bundleT5);
this.setCPtoBundle("*", ConfigurationPermission.TARGET, bundleT5, false);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
// let's create some configurations
for(int i=0; i<pids.length; i++) {
final String factoryPid = pids[i];
trace("Creating factory config " + factoryPid);
final Configuration c = this.cm.createFactoryConfiguration(factoryPid, null);
configs.add(c);
c.update(new Hashtable(){{
put("test", c.getPid());
put("factoryPid", factoryPid);
}});
if ( factoryPid.indexOf("Not") != -1 ) {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
assertEquals("Pid is wrong", c.getPid(), sync1_1.getProps().get("test"));
}
}
// now delete them - order doesn't really matter, but we use reverse order anyway
while ( configs.size() > 0 ) {
final Configuration c = (Configuration) configs.remove(configs.size() - 1);
final String pid = (String) c.getProperties().get("test");
final String factoryPid = (String) c.getProperties().get("factoryPid");
c.delete();
if ( factoryPid.indexOf("Not") != -1 ) {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
assertEquals("Pid is wrong", pid, sync1_1.getProps().get("test"));
assertEquals("Pid is not delete", Boolean.TRUE, sync1_1.getProps().get("_deleted_"));
}
}
} finally {
cleanUpForCallbackTest(bundleT5, null, null, null, list);
Iterator i = configs.iterator();
while ( i.hasNext() ) {
final Configuration c = (Configuration) i.next();
c.delete();
}
}
trace("Testing targeted factory pids...finished");
}
/**
* Test targeted pids
* Use a pid with a '|' .
*
* Enterprise 5.0 - ConfigAdmin 1.5
*/
public void testNegativeTargetedPid() throws Exception {
trace("Testing targeted pids...");
final Bundle bundleT5 = getContext().installBundle(
getWebServer() + "bundleT5.jar");
final String pid1 = Util.createPid("pid");
final String pid2 = Util.createPid("pid|targeted2");
final String[] pids = new String[] {pid1, pid2};
final List list = new ArrayList(5);
final List configs = new ArrayList();
try {
final SynchronizerImpl sync1_1 = new SynchronizerImpl("T5-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncT5_1));
this.startTargetBundle(bundleT5);
this.setCPtoBundle("*", ConfigurationPermission.TARGET, bundleT5, false);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
// let's create some configurations
for(int i=0; i<pids.length; i++) {
final String pid = pids[i];
trace("Creating config " + pid);
final Configuration c = this.cm.getConfiguration(pid, null);
configs.add(c);
c.update(new Hashtable(){
{
put("test", pid);
}
});
if ( pid.indexOf("|") == -1 ) {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
assertEquals("Pid is wrong", pid, sync1_1.getProps().get("test"));
}
}
// we now delete the configuration in reverse order
while ( configs.size() > 0 ) {
final Configuration c = (Configuration) configs.remove(configs.size() - 1);
final String pid = (String) c.getProperties().get("test");
c.delete();
if ( pid.indexOf("|") == -1 ) {
assertNoCallback(sync1_1, count1_1);
} else {
count1_1 = assertCallback(sync1_1, count1_1);
// remove, so no rebind
assertNull(sync1_1.getProps());
}
}
} finally {
cleanUpForCallbackTest(bundleT5, null, null, null, list);
Iterator i = configs.iterator();
while ( i.hasNext() ) {
final Configuration c = (Configuration) i.next();
c.delete();
}
}
trace("Testing targeted pids...finished");
}
/**
* Dynamic binding( configuration with null location and ManagedService)
*
* @spec ConfigurationAdmin.getConfiguration(String,String)
* @spec Configuration.getBundleLocation()
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.getProperties()
*
* @throws Exception
*/
public void testDynamicBinding() throws Exception {
Bundle bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
final String bundlePid = Util.createPid("bundlePid1");
Configuration conf = null;
ServiceRegistration reg = null;
Dictionary props = null;
/*
* 1. created newly with non-null location and after set to null. After
* that, ManagedService is registered.
*/
trace("############ 1 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, bundle1.getLocation());
props = new Hashtable();
props.put("StringKey", getName() + "-1");
conf.update(props);
conf.setBundleLocation(null);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
bundle1.stop();
assertEquals("Dynamic binding(STOPPED). Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
/*
* After the dynamically bound bundle has been uninstalled, the
* location must be reset to null.
*/
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
assertNull("Dynamic binding(UNINSTALLED)", conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
// conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/* 2. created newly with null location.(with properties) */
trace("############ 2 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
/* props is set. */
props = new Hashtable();
props.put("StringKey", getName() + "-2");
conf.update(props);
reg = null;
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
bundle1.stop();
assertEquals("Dynamic binding(STOPPED).Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
assertNull("Dynamic binding(UNINSTALLED)", conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
// conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/* 3. created newly with null location. (no properties) */
trace("############ 3 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
bundle1.stop();
assertEquals("Dynamic binding(STOPPED).Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
assertNull("Dynamic binding(UNINSTALLED)", conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
// conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* 4. created newly with null location and dynamic bound. Then
* explicitly set location. --> never dynamically unbound - bound
* anymore.
*/
trace("############ 4 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
props = new Hashtable();
props.put("StringKey", getName() + "-4");
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
conf.setBundleLocation(bundle1.getLocation());
bundle1.stop();
assertEquals("No more Dynamic binding(STOPPED). Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
assertEquals("No more Dynamic binding(UNINSTALLED)",
bundle1.getLocation(), conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
// conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* 5. dynamic binding and cm restart 1 (with properties).
*/
/**
* (a)install test bundle. (b)configure test bundle. (c)stop
* configuration admin service. (d)start configuration admin service
*
* ==> configuration is still bound to the target bundle
*/
trace("############ 5 testDynamicBinding()");
Bundle cmBundle = null;
try {
conf = cm.getConfiguration(bundlePid, null);
props = new Hashtable();
props.put("StringKey", getName() + "-5");
conf.update(props);
reg = null;
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue("ManagedService MUST be called back.", calledback);
bundle1.stop();
restartCM();
Sleep.sleep(SIGNAL_WAITING_TIME * 2);
Configuration[] confs = cm.listConfigurations(null);
assertNotNull("confs must NOT be empty:", confs);
assertEquals("confs.length must be one", 1, confs.length-existingConfigs.size());
for (int i = 0; i < confs.length; i++) {
conf = confs[i];
if (!existingConfigs.contains(conf.getPid())) {
trace("confs[" + i + "].getBundleLocation()=" + confs[i].getBundleLocation());
assertEquals("Dynamic binding(UNINSTALLED):confs[" + i
+ "].getBundleLocation() must be the target bundle", bundle1.getLocation(),
confs[i].getBundleLocation());
}
}
conf = cm.getConfiguration(bundlePid);
assertEquals(
"Restarted CM: Must be still bound to the target bundle.",
bundle1.getLocation(), conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* 6. dynamic binding and cm restart 2(with properties).
*/
/**
* (a)install test bundle. (b)configure test bundle. (c)stop
* configuration admin service. (d)uninstall test bundle. (e)start
* configuration admin service
*
* ==> configuration is still bound to the uninstalled bundle
*/
trace("############ 6 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
props = new Hashtable();
props.put("StringKey", getName() + "-6");
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
cmBundle = stopCmBundle();
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
bundle1.stop();
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
Sleep.sleep(SIGNAL_WAITING_TIME * 2);
Configuration[] confs = cm.listConfigurations(null);
assertNotNull("confs must NOT be empty:", confs);
assertEquals("confs.length must be one", 1, confs.length - existingConfigs.size());
for (int i = 0; i < confs.length; i++) {
conf = confs[i];
if (!existingConfigs.contains(conf.getPid())) {
trace("confs[" + i + "].getBundleLocation()=" + confs[i].getBundleLocation());
assertEquals("Dynamic binding(UNINSTALLED):confs[" + i + "].getBundleLocation() must be null",
null, confs[i].getBundleLocation());
}
}
conf = cm.getConfiguration(bundlePid);
assertEquals("Dynamic binding(UNINSTALLED): Must be Re-bound",
getContext().getBundle().getLocation(),
conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* 7. dynamic binding and cm restart 2 (with no properties).
*/
/**
* (a)install test bundle. (b)configure test bundle. (c)stop
* configuration admin service. (d)uninstall test bundle. (e)start
* configuration admin service
*
* ==> configuration is still bound to the uninstalled bundle
*/
trace("############ 7 testDynamicBinding()");
try {
conf = cm.getConfiguration(bundlePid, null);
// props = new Hashtable();
// props.put("StringKey", getName()+"-7");
// conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME);
cmBundle = stopCmBundle();
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
bundle1.stop();
Sleep.sleep(SIGNAL_WAITING_TIME);
bundle1.uninstall();
trace("Target Bundle is uninstalled. Wait for a while to check unbound.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
Sleep.sleep(SIGNAL_WAITING_TIME * 2);
conf = cm.getConfiguration(bundlePid, null);
assertEquals("Dynamic binding(UNINSTALLED): Must be reset to null",
null, conf.getBundleLocation());
conf = cm.getConfiguration(bundlePid);
assertEquals("Dynamic binding(UNINSTALLED): Must be Re-bound",
getContext().getBundle().getLocation(),
conf.getBundleLocation());
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
conf = null;
}
/*
* [In Progress] 8. After created newly with non-null location and
* ManagedService is registered, the location is set to null. What
* happens ?
*/
trace("############ 8 testDynamicBinding()");
ServiceRegistration reg2 = null;
Bundle bundle2 = null;
try {
conf = cm.getConfiguration(bundlePid, getWebServer()
+ "targetb1.jar");
props = new Hashtable();
props.put("StringKey", getName() + "-8");
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl("ID1");
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService MUST be called back in case conf has no properties.",
calledback);
assertEquals("Dynamic binding(STARTED)", bundle1.getLocation(),
conf.getBundleLocation());
conf.setBundleLocation(null);
trace("Wait for signal.");
// calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
// assertFalse("ManagedService MUST NOT be called back.",
// calledback);
// assertEquals("Must be still bound to the target bundle.",
// bundle1.getLocation(), conf.getBundleLocation());
// TODO: check if the unbound once (updated(null) is called)
// and bound againg (updated(props) is called ).
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count++);
assertTrue("ManagedService MUST be called back.", calledback);
conf.update(props);
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count++);
assertTrue("ManagedService MUST be called back.", calledback);
assertEquals("Must be bound to the target bundle. again.",
bundle1.getLocation(), conf.getBundleLocation());
bundle2 = getContext().installBundle(
getWebServer() + "targetb2.jar");
SynchronizerImpl sync2 = new SynchronizerImpl("ID2");
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
this.startTargetBundle(bundle2);
trace("Wait for signal.");
int count2 = 0;
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
//assertFalse(
// "ManagedService MUST NOT be called back in case conf has no properties.",
// calledback2);
assertTrue(
"ManagedService MUST be called back with null property.",
calledback2);
bundle1.stop();
assertEquals("Dynamic binding(STOPPED). Wait for a while.",
conf.getBundleLocation(), bundle1.getLocation());
calledback = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertFalse("ManagedService2 MUST NOT be called back.", calledback);
bundle1.uninstall();
trace("Dynamic binding(UNINSTALLED). Wait for a while.");
calledback2 = sync2
.waitForSignal(SIGNAL_WAITING_TIME * 2, ++count2);
/*
* Open issue. Should the newly dynamically bound ManagedService be
* called back ? Ikuo thinks yes while BJ thinks no. The
* implementator of this CT (Ikuo) thinks CT should not be strict in
* this point because it is not clear in the spec of version 1.3.
*/
// assertTrue("ManagedService MUST be called back.", calledback2);
if (!calledback2) {
count2--;
}
/*
* Open Issue: Ikuo thinks the Conf which got unbound from bundle1
* should get bound to any of other target bundles if other target
* bundle exists. However Felix thinks not (when Conf#update(props)
* is called, it will be bound. The implementator of this CT (Ikuo)
* thinks CT should not be strict in this point because it is not
* clear in the spec of version 1.3.
*/
// assertEquals("Dynamic binding(UNINSTALLED). Wait for a while.",
// bundle2.getLocation(), conf.getBundleLocation());
props.put("StringKey", "stringvalue2");
conf.update(props);
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService MUST be called back.", calledback2);
conf.delete();
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService MUST be called back.", calledback2);
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertFalse("ManagedService MUST NOT be called back.", calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
if (reg2 != null)
reg2.unregister();
reg2 = null;
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
conf = cm.getConfiguration(bundlePid);
if (conf != null)
conf.delete();
}
/*
* 9. Test dynamic bindings from getConfiguration(pid) and
* createConfiguration(pid) (Member Bug 2551)
*/
trace("############ 9 testDynamicBinding()");
String dynamicPid1 = Util.createPid("dynamicPid1");
String dynamicPid2 = Util.createPid("dynamicPid2");
String dynamicFactoryPid = Util.createPid("dynamicFactoryPid");
String dynamicFactoryPidInstance = null;
try {
props = new Hashtable();
props.put("StringKey", "String Value");
// make sure this bundle has enough permissions
this.setAppropriatePermission();
// ensure unbound configuration
conf = this.cm.getConfiguration(dynamicPid1, null);
assertNotNull("Configuration must exist for " + dynamicPid1, conf);
assertNull("Configuration must be new for " + dynamicPid1, conf.getProperties());
assertNull("Configuration for " + dynamicPid1 + " must be unbound",
this.getBundleLocationForCompare(conf));
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl("ID1");
reg = getContext().registerService(Synchronizer.class.getName(), sync, propsForSync1);
bundle1 = getContext().installBundle(getWebServer() + "targetb1.jar");
this.startTargetBundle(bundle1);
trace("Wait for signal.");
ServiceReference caref = bundle1.getBundleContext().getServiceReference(ConfigurationAdmin.class);
ConfigurationAdmin ca = (ConfigurationAdmin) bundle1.getBundleContext().getService(caref);
// ensure configuration 1 is bound to bundle1
conf = ca.getConfiguration(dynamicPid1);
assertNotNull("Configuration must exist for " + dynamicPid1, conf);
assertNotNull("Configuration must not be new for " + dynamicPid1, conf.getProperties());
assertEquals("Configuration for " + dynamicPid1 + " must be bound to " + bundle1.getLocation(),
bundle1.getLocation(), this.getBundleLocationForCompare(conf));
// ensure configuration 2 is bound to bundle1
conf = ca.getConfiguration(dynamicPid2);
assertNotNull("Configuration must exist for " + dynamicPid2, conf);
assertNull("Configuration must be new for " + dynamicPid2, conf.getProperties());
assertEquals("Configuration for " + dynamicPid2 + " must be bound to " + bundle1.getLocation(),
bundle1.getLocation(), this.getBundleLocationForCompare(conf));
conf.update(props);
// ensure factory configuration bound to bundle1
conf = ca.createFactoryConfiguration(dynamicFactoryPid);
dynamicFactoryPidInstance = conf.getPid();
assertNotNull("Factory Configuration must exist for " + dynamicFactoryPid, conf);
assertNull("Factory Configuration must be new for " + dynamicFactoryPid, conf.getProperties());
assertEquals(
"Factory Configuration for " + dynamicFactoryPid + " must be bound to " + bundle1.getLocation(),
bundle1.getLocation(), this.getBundleLocationForCompare(conf));
conf.update(props);
SynchronizerImpl sync2 = new SynchronizerImpl("SyncListener");
reg2 = getContext().registerService(ConfigurationListener.class.getName(), new SyncEventListener(sync2),
null);
// unsinstall the bundle, make sure configurations are unbound
this.uninstallBundle(bundle1);
// wait for three (CM_LOCATION_CHANGED) events
boolean threeEvents = sync2.waitForSignal(500, 3);
assertTrue("Expecting three CM_LOCATION_CHANGED events after bundle uninstallation", threeEvents);
// ensure configuration 1 is unbound
conf = this.cm.getConfiguration(dynamicPid1, null);
assertNotNull("Configuration must exist for " + dynamicPid1, conf);
assertNotNull("Configuration must not be new for " + dynamicPid1, conf.getProperties());
assertNull("Configuration for " + dynamicPid1 + " must be unbound", this.getBundleLocationForCompare(conf));
// ensure configuration 2 is unbound
conf = this.cm.getConfiguration(dynamicPid2, null);
assertNotNull("Configuration must exist for " + dynamicPid2, conf);
assertNotNull("Configuration must not be new for " + dynamicPid2, conf.getProperties());
assertNull("Configuration for " + dynamicPid2 + " must be unbound", this.getBundleLocationForCompare(conf));
// ensure factory configuration is unbound
conf = this.cm.getConfiguration(dynamicFactoryPidInstance, null);
assertNotNull("Configuration must exist for " + dynamicFactoryPidInstance, conf);
assertEquals("Configuration " + dynamicFactoryPidInstance + " must be factory configuration for "
+ dynamicFactoryPid, dynamicFactoryPid, conf.getFactoryPid());
assertNotNull("Configuration must not be new for " + dynamicFactoryPidInstance, conf.getProperties());
assertNull("Configuration for " + dynamicFactoryPidInstance + " must be unbound",
this.getBundleLocationForCompare(conf));
} finally {
if (reg != null) reg.unregister();
reg = null;
if (reg2 != null) reg2.unregister();
reg2 = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED) bundle1.uninstall();
bundle1 = null;
conf = cm.getConfiguration(dynamicPid1);
if (conf != null) conf.delete();
conf = cm.getConfiguration(dynamicPid2);
if (conf != null) conf.delete();
if (dynamicFactoryPidInstance != null) {
conf = cm.getConfiguration(dynamicFactoryPidInstance);
if (conf != null) conf.delete();
}
}
}
private void startTargetBundle(Bundle bundle) throws BundleException {
if (this.permissionFlag)
bundle.start();
else {
PermissionInfo[] defPis = permAdmin.getDefaultPermissions();
String[] locations = permAdmin.getLocations();
Map bundlePisMap = null;
if (locations != null) {
bundlePisMap = new HashMap(locations.length);
for (int i = 0; i < locations.length; i++) {
bundlePisMap.put(locations[i],
permAdmin.getPermissions(locations[i]));
}
}
this.resetPermissions();
bundle.start();
// this.printoutPermissions();
this.setPreviousPermissions(defPis, bundlePisMap);
}
}
private void setPreviousPermissions(PermissionInfo[] defPis,
Map bundlePisMap) {
PermissionInfo[] pis = null;
if (bundlePisMap != null)
for (Iterator keys = bundlePisMap.keySet().iterator(); keys
.hasNext();) {
String location = (String) keys.next();
if (location.equals(thisLocation))
pis = (PermissionInfo[]) bundlePisMap.get(location);
else
permAdmin.setPermissions(location,
(PermissionInfo[]) bundlePisMap.get(location));
}
permAdmin.setDefaultPermissions(defPis);
if (pis != null)
permAdmin.setPermissions(thisLocation, pis);
}
private PermissionInfo[] getDefaultPermissionInfos() {
if (permAdmin == null)
return null;
return permAdmin.getDefaultPermissions();
}
private void setInappropriatePermission() throws BundleException {
if (permAdmin == null)
return;
this.resetPermissions();
list.clear();
add(list, PropertyPermission.class.getName(), "*", "READ,WRITE");
add(list, PP, "*", "IMPORT,EXPORTONLY");
add(list, SP, "*", "GET,REGISTER");
// add(list, CP, "*", "CONFIGURE");
add(list, AP, "*", "*");
permissionFlag = false;
this.setBundlePermission(super.getContext().getBundle(), list);
}
private void setAppropriatePermission() throws BundleException {
if (permAdmin == null)
return;
this.resetPermissions();
list.clear();
add(list, PropertyPermission.class.getName(), "*", "READ,WRITE");
add(list, PP, "*", "IMPORT,EXPORTONLY");
add(list, SP, "*", "GET,REGISTER");
add(list, CP, "*", "CONFIGURE");
add(list, AP, "*", "*");
permissionFlag = true;
this.setBundlePermission(super.getContext().getBundle(), list);
}
/**
* TODO comments
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update()
* @spec Configuration.getProperties()
*
* @throws Exception
*/
public void testUpdate() throws Exception {
String pid = Util.createPid();
Configuration conf = cm.getConfiguration(pid);
Dictionary props = conf.getProperties();
assertNull("Properties in conf", props);
Hashtable newprops = new Hashtable();
newprops.put("somekey", "somevalue");
conf.update(newprops);
props = conf.getProperties();
assertNotNull("Properties in conf", props);
assertEquals("conf property 'somekey'", "somevalue",
props.get("somekey"));
Configuration conf2 = cm.getConfiguration(pid);
Dictionary props2 = conf2.getProperties();
assertNotNull("Properties in conf2", props2);
assertEquals("conf2 property 'somekey'", "somevalue",
props2.get("somekey"));
// assertSame("Same configurations", conf, conf2);
// assertEquals("Equal configurations", conf, conf2);
// assertEquals("Equal pids", conf.getPid(), conf2.getPid());
assertTrue("Equal configurations", equals(conf, conf2));
/* check returned properties are copied ones. */
Dictionary props3 = conf2.getProperties();
props3.put("KeyOnly3", "ValueOnly3");
assertTrue("Properties are copied", props2.get("KeyOnly3") == null);
/* Try to update with illegal configuration types */
Hashtable illegalprops = new Hashtable();
Collection v = new ArrayList();
v.add("a string");
v.add(Locale.getDefault());
illegalprops.put("somekey", "somevalue");
illegalprops.put("anotherkey", v);
String message = "updating with illegal properties";
try {
conf2.update(illegalprops);
/* A IllegalArgumentException should have been thrown */
failException(message, IllegalArgumentException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, IllegalArgumentException.class, e);
}
/* contains case variants of the same key name */
props2.put("SomeKey", "SomeValue");
message = "updating with illegal properties (case variants of the same key)";
try {
conf2.update(illegalprops);
/* A IllegalArgumentException should have been thrown */
failException(message, IllegalArgumentException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, IllegalArgumentException.class, e);
}
}
/**
* Tests if we really get the same configuration.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update()
* @spec Configuration.getPid()
* @throws Exception
*/
public void testEquals() throws Exception {
String pid = Util.createPid();
try {
Configuration conf1 = cm.getConfiguration(pid);
Configuration conf2 = cm.getConfiguration(pid);
assertEquals("Equal configurations", conf1, conf2);
assertTrue("Equal configurations", equals(conf1, conf2));
} finally {
cm.getConfiguration(pid).delete();
}
}
/**
* Tests listing of configurations.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec ConfigurationAdmin.listConfigurations(String)
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @throws Exception
*/
public void testListConfigurations() throws Exception {
this.setAppropriatePermission();
/* Create configurations */
/* pid starts with the same prefix */
final String pid11 = Util.createPid("pid11");
final String pid12 = Util.createPid("pid12");
final String pid21 = Util.createPid("pid21");
final String pid22 = Util.createPid("pid22");
final String pid31 = Util.createPid("pid31");
final String pid32 = Util.createPid("pid32");
/* pid does not start with the same prefix */
final String otherPid = "otherPid";
// this.cleanCM();
List configs = new ArrayList(2);
configs.add(cm.getConfiguration(pid11));
configs.add(cm.getConfiguration(pid12));
List updatedConfigs2 = new ArrayList(2);
updatedConfigs2.add(cm.getConfiguration(pid21));
updatedConfigs2.add(cm.getConfiguration(pid22));
Configuration otherConf = cm.getConfiguration(otherPid);
/* location is different */
List updatedConfigs3 = new ArrayList(2);
updatedConfigs3.add(cm.getConfiguration(pid31, neverlandLocation));
updatedConfigs3.add(cm.getConfiguration(pid32, neverlandLocation));
/*
* Update properties on some of configurations (to make them "active")
*/
for (int i = 0; i < updatedConfigs2.size(); i++) {
Hashtable props = new Hashtable();
props.put("someprop" + i, "somevalue" + i);
((Configuration) updatedConfigs2.get(i)).update(props);
}
for (int i = 0; i < updatedConfigs3.size(); i++) {
Hashtable props = new Hashtable();
props.put("someprop" + i, "somevalue" + i);
((Configuration) updatedConfigs3.get(i)).update(props);
}
try {
Configuration[] confs = cm.listConfigurations("(service.pid="
+ Util.createPid() + "*)");
/*
* Returned list must contain all of updateConfigs2 and
* updateConfigs3.
*/
checkIfAllUpdatedConfigs2and3isListed(confs, updatedConfigs2,
updatedConfigs3, null);
/* Inappropriate Permission */
this.setInappropriatePermission();
confs = cm.listConfigurations("(service.pid=" + Util.createPid()
+ "*)");
if (System.getSecurityManager() != null)
/* Returned list must contain all of updateConfigs2. */
checkIfAllUpdatedConfigs2isListed(confs, updatedConfigs2,
updatedConfigs3, null);
else
/*
* Returned list must contain all of updateConfigs2,
* updateConfigs3 and otherConf.
*/
checkIfAllUpdatedConfigs2and3isListed(confs, updatedConfigs2,
updatedConfigs3, otherConf);
/* Appropriate Permission */
this.setAppropriatePermission();
confs = cm.listConfigurations(null);
/*
* Returned list must contain all of updateConfigs2, updateConfigs3
* and otherConf.
*/
checkIfAllUpdatedConfigs2and3isListed(confs, updatedConfigs2,
updatedConfigs3, otherConf);
/* Inappropriate Permission */
this.setInappropriatePermission();
confs = cm.listConfigurations(null);
if (System.getSecurityManager() != null)
/*
* Returned list must contain all of updateConfigs2 and
* otherConf.
*/
checkIfAllUpdatedConfigs2isListed(confs, updatedConfigs2,
updatedConfigs3, otherConf);
else
/*
* Returned list must contain all of updateConfigs2,
* updateConfigs3 and otherConf.
*/
checkIfAllUpdatedConfigs2and3isListed(confs, updatedConfigs2,
updatedConfigs3, otherConf);
/* if the filter string is in valid */
/* must fail because of invalid filter. */
String message = "try to list configurations by invalid filter string.";
try {
cm.listConfigurations("(service.pid=" + Util.createPid() + "*");
/* A InvalidSyntaxException should have been thrown */
failException(message, InvalidSyntaxException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, InvalidSyntaxException.class, e);
}
}
/* Delete all used configurations */
finally {
for (int i = 0; i < configs.size(); i++) {
((Configuration) configs.get(i)).delete();
}
for (int i = 0; i < updatedConfigs2.size(); i++) {
((Configuration) updatedConfigs2.get(i)).delete();
}
for (int i = 0; i < updatedConfigs3.size(); i++) {
((Configuration) updatedConfigs3.get(i)).delete();
}
otherConf.delete();
}
this.setAppropriatePermission();
/* List all configurations and make sure they are all gone */
Configuration[] leftConfs = cm
.listConfigurations("(|(service.pid=" + pid11
+ ")(service.pid=" + pid12 + ")(service.pid=" + pid21
+ ")(service.pid=" + pid22 + ")(service.pid=" + pid31
+ ")(service.pid=" + pid32 + ")(service.pid="
+ otherPid + "))");
assertNull("Left configurations", leftConfs);
}
private void checkIfAllUpdatedConfigs2isListed(Configuration[] confs,
List updatedConfigs2, List updatedConfigs3, Configuration otherConf)
throws IOException, InvalidSyntaxException {
boolean otherFlag = false;
List removedConfigs2 = new ArrayList(updatedConfigs2.size());
confs = cm
.listConfigurations("(service.pid=" + Util.createPid() + "*)");
if (confs == null) {
fail("No configurations returned");
}
for (int i = 0; i < confs.length; i++) {
int index = isPartOf(confs[i], updatedConfigs2);
if (index != -1) {
pass(confs[i].getPid() + " was returned");
removedConfigs2.add(confs[i]);
} else if (otherConf != null && confs[i].equals(otherConf)) {
pass(confs[i].getPid() + " was returned");
otherFlag = true;
} else {
fail(confs[i].getPid() + " should not have been listed");
}
}
if (removedConfigs2.size() != updatedConfigs2.size() || otherFlag) {
fail("All config with nun-null properties and bound to the bundle location cannot be retrieved by listConfigurations().");
}
}
private void checkIfAllUpdatedConfigs2and3isListed(Configuration[] confs,
List updatedConfigs2, List updatedConfigs3, Configuration otherConf)
throws IOException, InvalidSyntaxException {
/*
* List all configurations and make sure that only the active
* configurations are returned
*/
List removedConfigs2 = new ArrayList(updatedConfigs2.size());
List removedConfigs3 = new ArrayList(updatedConfigs3.size());
boolean otherFlag = false;
if (confs == null) {
fail("No configurations returned");
}
for (int i = 0; i < confs.length; i++) {
int index = isPartOf(confs[i], updatedConfigs2);
if (index != -1) {
pass(confs[i].getPid() + " was returned");
removedConfigs2.add(confs[i]);
continue;
}
index = isPartOf(confs[i], updatedConfigs3);
if (index != -1) {
pass(confs[i].getPid() + " was returned");
removedConfigs3.add(confs[i]);
} else if (otherConf != null && equals(confs[i], otherConf)) {
pass(confs[i].getPid() + " was returned");
otherFlag = true;
} else if (!existingConfigs.contains(confs[i].getPid())) {
fail(confs[i].getPid() + " should not have been listed");
}
}
if (removedConfigs2.size() != updatedConfigs2.size()
|| removedConfigs3.size() != updatedConfigs3.size()
|| otherFlag) {
fail("All config with nun-null properties cannot be retrieved by listConfigurations().");
}
}
/**
* Tests to register a ManagedService when a configuration is existing for
* it.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getProperties()
* @spec Configuration.getBundleLocation()
*/
public void testManagedServiceRegistration() throws Exception {
this.setAppropriatePermission();
final String pid = Util.createPid("somepid");
/* create a configuration in advance, then register ManagedService */
Configuration conf = cm.getConfiguration(pid);
trace("created configuration has null properties.");
trace("Create and register a new the ManagedService");
Semaphore semaphore = new Semaphore();
ManagedServiceImpl ms = createManagedService(pid, semaphore);
trace("Wait until the ManagedService has gotten the update");
boolean calledBack = semaphore.waitForSignal(SIGNAL_WAITING_TIME);
assertTrue("ManagedService is called back", calledBack);
trace("Update done!");
conf.delete();
final String pid2 = Util.createPid("somepid2");
Configuration conf2 = cm.getConfiguration(pid2);
Hashtable props = new Hashtable();
props.put("somekey", "somevalue");
props.put("CAPITALkey", "CAPITALvalue");
conf2.update(props);
trace("created configuration has non-null properties.");
trace("Create and register a new the ManagedService");
trace("Wait until the ManagedService has gotten the update");
semaphore = new Semaphore();
ms = createManagedService(pid2, semaphore);
semaphore.waitForSignal();
trace("Update done!");
/*
* Add the two properties added by the CM and then check for equality in
* the properties
*/
props.put(Constants.SERVICE_PID, pid2);
// props.put(SERVICE_BUNDLE_LOCATION, "cm_TBC"); R3 does not include
// service.bundleLocation anymore!
assertEqualProperties("Properties equal?", props, ms.getProperties());
trace((String) ms.getProperties().get("service.pid"));
// trace((String) ms.getProperties().get("service.bundleLocation"));
trace(this.getBundleLocationForCompare(conf2));
/* OUTSIDE_OF_SPEC */
// assertNotSame("Properties same?", props, ms.getProperties());
conf2.delete();
}
private void printoutPropertiesForDebug(SynchronizerImpl sync) {
Dictionary props1 = sync.getProps();
if (props1 == null) {
System.out.println("props = null");
} else {
System.out.println("props = ");
for (Enumeration enums = props1.keys(); enums.hasMoreElements();) {
Object key = enums.nextElement();
System.out.println("\t(" + key + ", " + props1.get(key) + ")");
}
}
}
/**
* Register ManagedService Test 2.
*
* @throws Exception
*/
public void testManagedServiceRegistration2() throws Exception {
this.setAppropriatePermission();
Bundle bundle = getContext().installBundle(
getWebServer() + "targetb1.jar");
final String bundlePid = Util.createPid("bundlePid1");
ServiceRegistration reg = null;
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
trace("###################### A. testManagedServiceRegistration2.");
try {
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService MUST be called back even if no configuration.",
calledback);
assertNull("called back with null props", sync.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(bundlePid,
bundle.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
assertFalse("ManagedService must NOT be called back", calledback);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-A");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", getName() + "-A", props.get("StringKey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 2", 2, props.size());
/* stop and restart target bundle */
bundle.stop();
bundle.start();
trace("The target bundle has been started. Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
// printoutPropertiesForDebug(sync);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNull("called back with null props", sync.getProps());
Configuration[] confs = cm.listConfigurations(null);
assertTrue("confs must be empty:", confs == null
|| (existingConfigs.size() > 0 && confs.length == existingConfigs.size()));
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
/*
* B1. (1)Register ManagedService in advance. (2)create Configuration
* with different location and null props (3)setBundleLocation to the
* target bundle.
*/
trace("###################### B1. testManagedServiceRegistration2.");
try {
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService must be called back even if no configuration.",
calledback);
assertNull("called back with null props", sync.getProps());
trace("The configuration with different location is being created ");
Configuration conf = cm.getConfiguration(bundlePid,
neverlandLocation);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
this.printoutPropertiesForDebug(sync);
assertFalse("ManagedService must NOT be called back", calledback);
/* The conf has null props. */
trace("The configuration is being set to the target bundle");
conf.setBundleLocation(bundle.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
/*
* The spec seems unclear whether the ManagedService registered by
* the newly bound bundle should be called back with null or not
* called back. The implementator of this CT (Ikuo) thinks CT should
* accept either case of (a) No callback. (b) callback with null.
* Otherwise, it fails. Spec of version 1.3
*/
if (calledback) {
count++;
assertNull(
"The props called back MUST be null, if the ManagedService is called back.",
sync.getProps());
}
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B1");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", getName() + "-B1", props.get("StringKey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 2", 2, props.size());
trace("The configuration is being updated to null.");
/* props is reset */
conf.update(new Hashtable(0));
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("Size of props must be 1", 1, props.size());
conf.update(props);
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
trace("The configuration is being set to different location");
conf.setBundleLocation(neverlandLocation);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNull("called back with null props", sync.getProps());
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertFalse("ManagedService must Not be called back", calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
/*
* B2. (1)create Configuration with different location and non-null
* props. (2) Register ManagedService. (3)setBundleLocation to the
* target bundle.
*/
trace("###################### B2. testManagedServiceRegistration2.");
try {
trace("The configuration with different location is being created ");
Configuration conf = cm.getConfiguration(bundlePid,
neverlandLocation);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B2");
conf.update(props);
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
//assertFalse(
// "ManagedService must NOT be called back even if no configuration.",
// calledback);
assertTrue(
"ManagedService MUST be called back with null parameter when there is no configuration.",
calledback);
trace("The configuration is being updated ");
props.put("StringKey", "stringvalue2");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
this.printoutPropertiesForDebug(sync);
assertFalse("ManagedService must NOT be called back", calledback);
/* The conf has non-null props. */
trace("The configuration is being set to the target bundle");
conf.setBundleLocation(bundle.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
/*
* XXX Felix and Ikuo think the ManagedService registered by the
* newly bound bundle should be called back with the props. However,
* BJ thinks no. The implementator of this CT (Ikuo) thinks CT
* should not check it because it is unclear in the spec of version
* 1.3.
*/
// assertTrue("ManagedService must be called back", calledback);
// assertFalse("ManagedService must NOT be called back",
// calledback);
if (calledback) {
++count;
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", "stringvalue2", props.get("StringKey"));
assertEquals("Size of props must be 2", 2, props.size());
}
trace("The configuration is being updated ");
props.put("StringKey", "stringvalue3");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", "stringvalue3", props.get("StringKey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 2", 2, props.size());
trace("The configuration is being set to different location");
conf.setBundleLocation(neverlandLocation);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
/*
* XXX Felix and Ikuo think the ManagedService registered by the
* newly bound bundle should be called back with null. However, BJ
* thinks no. The implementator of this CT (Ikuo) thinks CT should
* not check it strictly because it is unclear in the spec of
* version 1.3.
*/
// assertTrue("ManagedService must be called back", calledback);
if (calledback) {
++count;
assertNull("called back with null props", sync.getProps());
}
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertFalse("ManagedService must Not be called back", calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
/*
* B3. (1)create Configuration with different location and null props.
* (2) Register ManagedService. (3)setBundleLocation to the target
* bundle.
*/
trace("###################### B3. testManagedServiceRegistration2.");
try {
trace("The configuration with different location is being created ");
Configuration conf = cm.getConfiguration(bundlePid,
neverlandLocation);
trace("The configuration is being updated ");
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
//assertFalse(
// "ManagedService must NOT be called back even if no configuration.",
// calledback);
assertTrue(
"ManagedService MUST be called back with null parameter when there is no configuration.",
calledback);
assertNull("called back with null props", sync.getProps());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B3");
conf.update(props);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
this.printoutPropertiesForDebug(sync);
assertFalse("ManagedService must NOT be called back", calledback);
/* The conf has non-null props. */
trace("The configuration is being set to the target bundle");
conf.setBundleLocation(bundle.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid, props.get(Constants.SERVICE_PID));
assertEquals("pid", getName() + "-B3", props.get("StringKey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 2", 2, props.size());
trace("The configuration is being set to different location");
conf.setBundleLocation(neverlandLocation);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
/*
* XXX Felix and Ikuo think the ManagedService registered by the
* newly bound bundle should be called back with null. However, BJ
* thinks no. The implementator of this CT (Ikuo) thinks CT should
* not check it strictly because it is unclear in the spec of
* version 1.3.
*/
// assertTrue("ManagedService must be called back", calledback);
if (calledback) {
++count;
assertNull("called back with null props", sync.getProps());
}
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertFalse("ManagedService must NOT be called back", calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
/*
* C. Configuration Admin Service is stopped once. After a while, it
* restarts.
*
* 1.Register ManagedService in advance. 2.create Configuration with
* different location. 3.setBundleLocation to the target bundle.
*/
Bundle cmBundle = stopCmBundle();
try {
int count = 0;
SynchronizerImpl sync = new SynchronizerImpl();
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle);
/* restart where no configuration. */
trace("Wait for restart cm bundle.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
trace("Wait for signal.");
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService is Called back even if no configuration.",
calledback);
this.cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
/* Create configuration and stop/start cm. */
Configuration conf = cm.getConfiguration(bundlePid,
bundle.getLocation());
cmBundle = stopCmBundle();
trace("Wait for restart cm bundle.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService is Called back.", calledback);
this.cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
//conf.delete();
cm.getConfiguration(bundlePid).delete();
/* Create configuration with null location and stop/start cm. */
conf = cm.getConfiguration(bundlePid, null);
cmBundle = stopCmBundle();
trace("Wait for restart cm bundle.");
Sleep.sleep(SIGNAL_WAITING_TIME);
startCmBundle(cmBundle);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue(
"ManagedService is Called back even if configuration with null.",
calledback);
} finally {
if (reg != null)
reg.unregister();
reg = null;
bundle.stop();
cm.getConfiguration(bundlePid).delete();
}
}
/**
* Register ManagedService in advance. ManagedService has multiple pids.
* Then create Configuration.
*
* @throws Exception
*/
public void testManagedServiceRegistrationWithMultiplPIDs()
throws Exception {
this.setAppropriatePermission();
try {
trace("########## 1(array) testManagedServiceRegistrationWithMultiplPIDs");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_MODE,
org.osgi.test.cases.cm.shared.Constants.MODE_ARRAY);
internalTestRegisterManagedServiceWithMultiplePIDs();
trace("########## 1(list) testManagedServiceRegistrationWithMultiplPIDs");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_MODE,
org.osgi.test.cases.cm.shared.Constants.MODE_LIST);
internalTestRegisterManagedServiceWithMultiplePIDs();
trace("########## 1(set) testManagedServiceRegistrationWithMultiplPIDs");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_MODE,
org.osgi.test.cases.cm.shared.Constants.MODE_SET);
internalTestRegisterManagedServiceWithMultiplePIDs();
} finally {
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_MODE,
org.osgi.test.cases.cm.shared.Constants.MODE_UNARY);
}
}
private void internalTestRegisterManagedServiceWithMultiplePIDs()
throws BundleException, IOException {
final String bundlePid1 = Util.createPid("bundlePid1");
final String bundlePid2 = Util.createPid("bundlePid2");
ServiceRegistration reg = null;
Bundle bundle1 = null;
try {
bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
SynchronizerImpl sync = new SynchronizerImpl();
trace("1 sync.getCount()=" + sync.getCount());
reg = getContext().registerService(Synchronizer.class.getName(),
sync, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
int count = 0;
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME,
++count);
assertTrue(
"ManagedService MUST be called back even if no configuration.",
calledback);
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
if (!calledback)
--count;
trace("sync.getCount()=" + sync.getCount());
trace("The configuration1 is being created");
trace("sync.getCount()=" + sync.getCount());
Configuration conf1 = cm.getConfiguration(bundlePid1,
bundle1.getLocation());
trace("sync.getCount()=" + sync.getCount());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
assertFalse("ManagedService must NOT be called back", calledback);
trace("The configuration2 is being created");
Configuration conf2 = cm.getConfiguration(bundlePid2,
bundle1.getLocation());
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
trace("sync.getCount()=" + sync.getCount());
assertFalse("ManagedService must NOT be called back", calledback);
trace("The configuration1 is being updated ");
Dictionary props1 = new Hashtable();
props1.put("StringKey1", "stringvalue1");
conf1.update(props1);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
trace("sync.getCount()=" + sync.getCount());
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
Dictionary props = sync.getProps();
assertEquals("pid", bundlePid1, props.get(Constants.SERVICE_PID));
assertEquals("pid", "stringvalue1", props.get("StringKey1"));
trace("The configuration2 is being updated ");
Dictionary props2 = new Hashtable();
props2.put("StringKey1", "stringvalue1");
props2.put("StringKey2", "stringvalue2");
conf2.update(props2);
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
assertNotNull("null props must be called back", sync.getProps());
props = sync.getProps();
assertEquals("pid", bundlePid2, props.get(Constants.SERVICE_PID));
assertEquals("pid", "stringvalue1", props.get("StringKey1"));
assertEquals("pid", "stringvalue2", props.get("StringKey2"));
assertEquals("Size of props must be 3", 3, props.size());
trace("The configuration1 is being deleted ");
conf1.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
trace("The configuration2 is being deleted ");
conf2.delete();
trace("Wait for signal.");
calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue("ManagedService must be called back", calledback);
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
} finally {
if (reg != null)
reg.unregister();
reg = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
}
}
/**
* Register ManagedService in advance. Then create Configuration.
*
* @throws Exception
*/
public void testManagedServiceRegistrationDuplicatedTargets()
throws Exception {
this.setAppropriatePermission();
Bundle bundle2 = getContext().installBundle(
getWebServer() + "targetb2.jar");
final String bundlePid = Util.createPid("bundlePid1");
ServiceRegistration reg2 = null;
/*
* A. One bundle registers duplicated ManagedService. Both of them must
* be called back.
*/
trace("################## A testManagedServiceRegistrationDuplicatedTargets()");
try {
SynchronizerImpl sync2 = new SynchronizerImpl();
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_DUPCOUNT,
"2");
this.startTargetBundle(bundle2);
trace("Wait for signal.");
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertTrue(
"Both ManagedService MUST be called back even if no configuration.",
calledback2);
assertNull("called back with null props", sync2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(bundlePid,
bundle2.getLocation());
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 3);
assertFalse("ManagedService must NOT be called back", calledback2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-A");
conf.update(props);
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 4);
assertTrue("Both ManagedService must be called back", calledback2);
/* stop and restart target bundle */
bundle2.stop();
bundle2.start();
trace("The target bundle has been stopped and re-started. Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 6);
assertTrue("Both ManagedService must be called back", calledback2);
// printoutPropertiesForDebug(sync);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 8);
assertTrue("Both ManagedService must be called back", calledback2);
assertNull("null props must be called back", sync2.getProps());
} finally {
if (reg2 != null)
reg2.unregister();
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
}
/*
* B1. (1)No Configuration. (2)two bundles register duplicated
* ManagedService. ==> Only one, firstly registered, must be called
* back.
*/
trace("################## B1 testManagedServiceRegistrationDuplicatedTargets()");
reg2 = null;
ServiceRegistration reg1 = null;
Bundle bundle1 = getContext().installBundle(
getWebServer() + "targetb1.jar");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_DUPCOUNT,
"1");
bundle2 = getContext().installBundle(getWebServer() + "targetb2.jar");
try {
SynchronizerImpl sync2 = new SynchronizerImpl("ID2");
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
this.startTargetBundle(bundle2);
trace("Wait for signal.");
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 1);
assertTrue(
"ManagedService MUST be called back even if no configuration.",
calledback2);
assertNull("null props must be called back", sync2.getProps());
SynchronizerImpl sync1 = new SynchronizerImpl("ID1");
reg1 = getContext().registerService(Synchronizer.class.getName(),
sync1, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
boolean calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, 1);
assertTrue(
"ManagedService MUST be called back even if no configuration.",
calledback1);
trace("The configuration is being created");
Configuration[] confs = cm.listConfigurations(null);
assertTrue("confs must be empty:", confs == null
|| (existingConfigs.size() > 0 && confs.length == existingConfigs.size()));
Configuration conf = cm.getConfiguration(bundlePid,
bundle2.getLocation());
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 2);
this.printoutPropertiesForDebug(sync2);
assertFalse("ManagedService must NOT be called back", calledback2);
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertFalse("ManagedService must NOT be called back", calledback1);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B1");
conf.update(props);
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertFalse("ManagedService must NOT be called back", calledback1);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, 3);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
assertNull("null props must be called back", sync2.getProps());
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, 2);
assertFalse("ManagedService must NOT be called back", calledback1);
} finally {
if (reg1 != null)
reg1.unregister();
reg1 = null;
if (reg2 != null)
reg2.unregister();
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
}
/*
* B2. (1) Create new Conf with null props. (2)two bundles register
* duplicated ManagedService. ==> Only one, firstly registered, must be
* called back.
*/
trace("################## B2 testManagedServiceRegistrationDuplicatedTargets()");
reg2 = null;
reg1 = null;
bundle1 = getContext().installBundle(getWebServer() + "targetb1.jar");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_DUPCOUNT,
"1");
bundle2 = getContext().installBundle(getWebServer() + "targetb2.jar");
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(bundlePid,
bundle2.getLocation());
SynchronizerImpl sync2 = new SynchronizerImpl("ID2");
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
this.startTargetBundle(bundle2);
trace("Wait for signal.");
int count2 = 0;
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME,
++count2);
assertTrue(
"ManagedService MUST be called back even if configuration has no props.",
calledback2);
assertNull("null props must be called back", sync2.getProps());
SynchronizerImpl sync1 = new SynchronizerImpl("ID1");
reg1 = getContext().registerService(Synchronizer.class.getName(),
sync1, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
int count1 = 0;
boolean calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME,
++count1);
//assertFalse("ManagedService MUST NOT be called back even.",
// calledback1);
assertTrue(
"ManagedService MUST be called back even if deffirent bound location.",
calledback1);
assertNull("null props must be called back", sync1.getProps());
Configuration[] confs = cm.listConfigurations(null);
assertTrue("confs must be empty:", confs == null
|| (existingConfigs.size() > 0 && confs.length == existingConfigs.size()));
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B2");
conf.update(props);
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, count1 + 1);
assertFalse("ManagedService must NOT be called back", calledback1);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
assertNull("null props must be called back", sync2.getProps());
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, count1 + 1);
assertFalse("ManagedService must NOT be called back", calledback1);
} finally {
if (reg1 != null)
reg1.unregister();
reg1 = null;
if (reg2 != null)
reg2.unregister();
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
}
/*
* B3. (1) Create new Conf with non-null props. (2)two bundles register
* duplicated ManagedService. ==> Only one, firstly registered, must be
* called back.
*/
trace("################## B3 testManagedServiceRegistrationDuplicatedTargets()");
reg2 = null;
reg1 = null;
bundle1 = getContext().installBundle(getWebServer() + "targetb1.jar");
System.setProperty(
org.osgi.test.cases.cm.shared.Constants.SYSTEMPROP_KEY_DUPCOUNT,
"1");
bundle2 = getContext().installBundle(getWebServer() + "targetb2.jar");
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(bundlePid,
bundle2.getLocation());
Dictionary props = new Hashtable();
props.put("StringKey", getName() + "-B3");
conf.update(props);
SynchronizerImpl sync2 = new SynchronizerImpl("ID2");
reg2 = getContext().registerService(Synchronizer.class.getName(),
sync2, propsForSync2);
this.startTargetBundle(bundle2);
trace("Wait for signal.");
int count2 = 0;
boolean calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME,
++count2);
assertTrue("ManagedService MUST be called back.", calledback2);
assertNotNull("called back with null props", sync2.getProps());
SynchronizerImpl sync1 = new SynchronizerImpl("ID1");
reg1 = getContext().registerService(Synchronizer.class.getName(),
sync1, propsForSync1);
this.startTargetBundle(bundle1);
trace("Wait for signal.");
int count1 = 0;
boolean calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME,
++count1);
//assertFalse("ManagedService MUST NOT be called back.", calledback1);
assertTrue(
"ManagedService MUST be called back even if deffirent bound location.",
calledback1);
assertNull("null props must be called back", sync1.getProps());
Configuration[] confs = cm.listConfigurations(null);
assertNotNull("confs must NOT be empty:", confs);
trace("The configuration is being updated ");
props.put("StringKey2", "stringvalue2");
conf.update(props);
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, count1 + 1);
assertFalse("ManagedService must NOT be called back", calledback1);
trace("The configuration is being deleted ");
conf.delete();
trace("Wait for signal.");
calledback2 = sync2.waitForSignal(SIGNAL_WAITING_TIME, ++count2);
assertTrue("ManagedService firstly registered must be called back",
calledback2);
assertNull("null props must be called back", sync2.getProps());
calledback1 = sync1.waitForSignal(SIGNAL_WAITING_TIME, count1 + 1);
assertFalse("ManagedService must NOT be called back", calledback1);
} finally {
if (reg1 != null)
reg1.unregister();
reg1 = null;
if (reg2 != null)
reg2.unregister();
reg2 = null;
if (bundle2 != null && bundle2.getState() != Bundle.UNINSTALLED)
bundle2.uninstall();
bundle2 = null;
if (bundle1 != null && bundle1.getState() != Bundle.UNINSTALLED)
bundle1.uninstall();
bundle1 = null;
}
}
private Bundle stopCmBundle() {
ServiceReference reference = this.getContext().getServiceReference(ConfigurationAdmin.class.getName());
Bundle cmBundle = reference.getBundle();
try {
cmBundle.stop();
} catch (BundleException be) {
fail("Error stopping CM Bundle: " + be);
}
cm = null;
return cmBundle;
}
private void assignCm() {
cm = (ConfigurationAdmin) getService(ConfigurationAdmin.class);
}
private void startCmBundle(Bundle cmBundle) {
try {
cmBundle.start();
} catch (BundleException be) {
fail("Error starting CM Bundle: " + be);
}
assignCm();
}
private Dictionary getManagedProperties(String pid) throws Exception {
Semaphore semaphore = new Semaphore();
ManagedServiceImpl ms = createManagedService(pid, semaphore);
semaphore.waitForSignal();
return ms.getProperties();
}
/**
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getProperties()
* @throws Exception
*/
public void testManagedProperties() throws Exception {
String pid = Util.createPid("somepid");
/* Set up the configuration */
Configuration conf = cm.getConfiguration(pid);
/* Put all legal types in the properties and update */
Hashtable props = new Hashtable();
props.put("StringKey", getName());
props.put("IntegerKey", new Integer(12));
props.put("LongKey", new Long(-29));
props.put("FloatKey", new Float(921.14));
props.put("DoubleKey", new Double(1827.234));
props.put("ByteKey", new Byte((byte) 127));
props.put("ShortKey", new Short((short) 1));
// props.put("BigIntegerKey", new BigInteger("123"));
// props.put("BigDecimalkey", new BigDecimal(9872.7643));
props.put("CharacterKey", new Character('N'));
props.put("BooleanKey", new Boolean(true));
Collection v = new ArrayList();
v.add(getName());
// ### is now invalid ....
// v.addElement(new Integer(12));
// v.addElement(new Long(-29));
// v.addElement(new Float(921.14));
// v.addElement(new Double(1827.234));
// v.addElement(new Byte((byte) 127));
// v.addElement(new Short((short) 1));
// v.addElement(new BigInteger("123"));
// v.addElement(new BigDecimal(9872.7643));
// v.addElement(new Character('N'));
// v.addElement(new Boolean(true));
// v.addElement(new String[] {"firststring", "secondstring"});
// ### end invalid
props.put("collectionkey", v);
props.put("StringArray", new String[] { "string1", "string2" });
props.put("IntegerArray", new Integer[] { new Integer(1),
new Integer(2) });
props.put("LongArray", new Long[] { new Long(1), new Long(2) });
props.put("FloatArray", new Float[] { new Float(1.1), new Float(2.2) });
props.put("DoubleArray", new Double[] { new Double(1.1),
new Double(2.2) });
props.put("ByteArray", new Byte[] { new Byte((byte) -1),
new Byte((byte) -2) });
props.put("ShortArray", new Short[] { new Short((short) 1),
new Short((short) 2) });
// props.put("BigIntegerArray", new BigInteger[] {
// new BigInteger("1"), new BigInteger("2")
// }
//
// );
// props.put("BigDecimalArray", new BigDecimal[] {
// new BigDecimal(1.1), new BigDecimal(2.2)
// }
//
// );
props.put("CharacterArray", new Character[] { new Character('N'),
new Character('O') });
props.put("BooleanArray", new Boolean[] { new Boolean(true),
new Boolean(false) });
// ### invalid
// Vector v1 = new Vector();
// v1.addElement(new Vector());
// v1.addElement("Anystring");
// props.put("VectorArray", new Vector[] {v1, new Vector()});
props.put("CAPITALkey", "CAPITALvalue");
conf.update(props);
/* Register a managed service and get the properties */
Dictionary msprops = getManagedProperties(pid);
/*
* Add the two properties added by the CM and then check for equality in
* the properties (including preserved case)
*/
props.put(Constants.SERVICE_PID, pid);
// props.put(SERVICE_BUNDLE_LOCATION, "cm_TBC"); R3 does not include
// service.bundleLocation anymore!
assertEqualProperties("Properties equal?", props, msprops);
/* Check if the properties are case independent */
String s = (String) msprops.get("sTringkeY");
assertEquals("case independant properties", getName(), s);
Hashtable illegalprops = new Hashtable();
illegalprops.put("exception", new Exception());
String message = "Exception is not a legal type";
try {
conf.update(illegalprops);
/* A IllegalArgumentException should have been thrown */
failException(message, IllegalArgumentException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, IllegalArgumentException.class, e);
}
/* TODO: Add more illegal types (inside collections etc) */
}
// public void testUpdatedProperties() throws Exception {
// /* Put all legal types in the properties and update */
// /* Get the properties again */
// /* Check if the properties are equals */
// /* Check if the properties have preserved the case */
// /* Check if the properties are case independent */
// }
/**
* Test created Factory configuration without location.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getProperties()
* @spec Configuration.getBundleLocation()
* @throws Exception
*/
public void testCreateFactoryConfiguration() throws Exception {
commonTestCreateFactoryConfiguration(false, getLocation());
}
/**
* Test created Factory configuration with location.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String,String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getProperties()
* @spec Configuration.getBundleLocation()
* @throws Exception
*/
public void testCreateFactoryConfigurationWithLocation() throws Exception {
commonTestCreateFactoryConfiguration(true, neverlandLocation);
}
/**
* Test created Factory configuration with null location.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String,String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getProperties()
* @spec Configuration.getBundleLocation()
* @throws Exception
*/
public void testCreateFactoryConfigurationWithNullLocation()
throws Exception {
commonTestCreateFactoryConfiguration(true, null);
}
private void commonTestCreateFactoryConfiguration(boolean withLocation,
String location) throws Exception {
final int NUMBER_OF_CONFIGS = 3;
final String factorypid = Util.createPid("somefactorypid");
final List pids = new ArrayList();
final List configs = new ArrayList();
// Inappropriate Permission
this.setInappropriatePermission();
pids.add(factorypid);
for (int i = 0; i < NUMBER_OF_CONFIGS; i++) {
Configuration conf = null;
if (withLocation) {
/*
* Without appropriate ConfigurationPermission, create
* FactoryConfiguration with specfied location.
*/
String message = "try to create factory configuration without appropriate ConfigurationPermission.";
try {
conf = cm.createFactoryConfiguration(factorypid, location);
/*
* A SecurityException should have been thrown if security
* is enabled
*/
if (System.getSecurityManager() != null)
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
/* Check that we got the correct exception */
assertException(message, SecurityException.class, e);
/*
* A SecurityException should not have been thrown if
* security is not enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
}
continue;
} else {
/*
* Even appropriate ConfigurationPermission,
* createFactoryConfiguration(factorypid) must be succeed
*/
conf = cm.createFactoryConfiguration(factorypid);
}
configs.add(conf);
trace("pid: " + conf.getPid());
assertTrue("Unique pid", !pids.contains(conf.getPid()));
assertEquals("Correct factory pid", factorypid,
conf.getFactoryPid());
assertNull("No properties", conf.getProperties());
assertEquals("Correct location", location,
getBundleLocationForCompare(conf));
/* Add the pid to the list */
pids.add(conf.getPid());
}
for (int i = 0; i < configs.size(); i++) {
Configuration conf = (Configuration) configs.get(i);
conf.delete();
}
// Appropriate Permission
pids.clear();
configs.clear();
this.setAppropriatePermission();
pids.add(factorypid);
for (int i = 0; i < NUMBER_OF_CONFIGS; i++) {
Configuration conf = null;
if (withLocation) {
conf = cm.createFactoryConfiguration(factorypid, location);
} else {
conf = cm.createFactoryConfiguration(factorypid);
}
configs.add(conf);
trace("pid: " + conf.getPid());
assertTrue("Unique pid", !pids.contains(conf.getPid()));
assertEquals("Correct factory pid", factorypid,
conf.getFactoryPid());
assertNull("No properties", conf.getProperties());
assertEquals("Correct location", location,
this.getBundleLocationForCompare(conf));
/* Add the pid to the list */
pids.add(conf.getPid());
}
for (int i = 0; i < configs.size(); i++) {
Configuration conf = (Configuration) configs.get(i);
conf.delete();
}
}
private String getBundleLocationForCompare(Configuration conf)
throws BundleException {
String location = null;
if (this.permissionFlag) {
try {
location = conf.getBundleLocation();
} catch (SecurityException se) {
// Bug 2539: Need to be hard on granting appropriate permission
System.out.println("Temporarily grant CONFIGURE(" + thisLocation
+ ") to get location of configuration " + conf.getPid());
List perms = getBundlePermission(thisBundle);
try {
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
location = conf.getBundleLocation();
} catch (SecurityException se2) {
throw se;
} finally {
System.out.println("Resetting permissions for " + thisLocation + " to: " + perms);
resetBundlePermission(thisBundle, perms);
}
}
} else {
this.setAppropriatePermission();
location = conf.getBundleLocation();
this.setInappropriatePermission();
}
return location;
}
public void testFactoryConfigurationCollision() throws IOException, InvalidSyntaxException, BundleException {
final String factoryPid = Util.createPid("factoryPid1");
final Configuration cf = cm.createFactoryConfiguration( factoryPid, null );
assertNotNull( cf );
final String pid = cf.getPid();
List list = new ArrayList(3);
Bundle bundle = getContext().installBundle(getWebServer() + "bundleT1.jar");
try
{
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(), sync1_1, propsForSyncF1_1));
this.startTargetBundle(bundle);
trace("Wait for signal.");
int count1_1 = 0;
assertNoCallback(sync1_1, count1_1);
assertNotNull( "Configuration must have PID", pid );
assertEquals( "Factory configuration must have requested factory PID", factoryPid, cf.getFactoryPid() );
// assert getConfiguration returns the same configurtion
final Configuration c1 = cm.getConfiguration( pid, null );
assertEquals( "getConfiguration must retrieve required PID", pid, c1.getPid() );
assertEquals( "getConfiguration must retrieve new factory configuration", factoryPid, c1.getFactoryPid() );
assertNull( "Configuration must not have properties", c1.getProperties() );
assertNoCallback(sync1_1, count1_1);
// restart config admin and verify getConfiguration persisted
// the new factory configuration as such
restartCM();
assertNotNull( "Config Admin Service missing", cm );
assertNoCallback(sync1_1, count1_1);
final Configuration c2 = cm.getConfiguration( pid, null );
assertEquals( "getConfiguration must retrieve required PID", pid, c2.getPid() );
assertEquals( "getConfiguration must retrieve new factory configuration from persistence", factoryPid, c2.getFactoryPid() );
assertNull( "Configuration must not have properties", c2.getProperties() );
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
c2.update( props );
count1_1 = assertCallback(sync1_1, count1_1);
props = sync1_1.getProps();
assertEquals( "stringvalue", props.get( "StringKey" ) );
final Configuration[] cfs = cm.listConfigurations( "(" + ConfigurationAdmin.SERVICE_FACTORYPID + "="
+ factoryPid + ")" );
assertNotNull( "Expect at least one configuration", cfs );
assertEquals( "Expect exactly one configuration", 1, cfs.length );
assertEquals( cf.getPid(), cfs[0].getPid() );
assertEquals( cf.getFactoryPid(), cfs[0].getFactoryPid() );
}
finally
{
// make sure no configuration survives ...
this.cleanUpForCallbackTest(bundle, null, null, list);
cm.getConfiguration( pid, null ).delete();
}
}
/**
* Test Managed Service Factory.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec Configuration.getPid()
* @spec Configuration.getFactoryPid()
* @spec Configuration.getProperties()
* @spec ManagedServiceFactory.updated(String,Dictionary)
* @throws Exception
*/
public void testManagedServiceFactory() throws Exception {
final int NUMBER_OF_CONFIGS = 3;
String factorypid = Util.createPid("somefactorypid");
Hashtable configs = new Hashtable();
/* Create some factory configurations */
for (int i = 0; i < NUMBER_OF_CONFIGS; i++) {
Configuration conf = cm.createFactoryConfiguration(factorypid);
Hashtable ht = new Hashtable();
ht.put("test.field", i + "");
conf.update(ht);
trace("pid: " + conf.getPid());
configs.put(conf.getPid(), conf);
}
try {
Semaphore semaphore = new Semaphore();
/* Register a factory */
ManagedServiceFactoryImpl msf = new ManagedServiceFactoryImpl(
"msf", "testprop", semaphore);
Hashtable properties = new Hashtable();
properties.put(Constants.SERVICE_PID, factorypid);
properties.put(ConfigurationAdmin.SERVICE_FACTORYPID, factorypid);
registerService(ManagedServiceFactory.class.getName(), msf,
properties);
for (int i = 0; i < NUMBER_OF_CONFIGS; i++) {
trace("Wait for signal #" + i);
semaphore.waitForSignal();
trace("Signal #" + i + " arrived");
}
trace("All signals have arrived");
} finally {
Enumeration keys = configs.keys();
while (keys.hasMoreElements()) {
Configuration conf = (Configuration) configs.get(keys
.nextElement());
conf.delete();
}
}
}
/**
* Tests a configuration listener update event notification from a
* configuration service. The event data should match the data that
* originated the event (pid, factorypid...).
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @spec Configuration.update(Dictionary)
* @throws Exception
*/
public void testUpdateConfigEvent() throws Exception {
ConfigurationListenerImpl cl = null;
String pid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
SynchronizerImpl synchronizer = new SynchronizerImpl();
/* Set up the configuration */
Configuration conf = cm.getConfiguration(pid);
Hashtable props = new Hashtable();
props.put("key", "value1");
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
try {
conf.update(props);
trace("Wait until the ConfigurationListener has gotten the update");
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType());
assertNull("Config Factory event pid null", cl.getFactoryPid());
assertNotNull("Config event reference null", cl.getReference());
ConfigurationAdmin admin = (ConfigurationAdmin) getContext()
.getService(cl.getReference());
try {
assertNotNull("Configuration Admin from event", admin);
Configuration config = admin.getConfiguration(cl.getPid());
assertNotNull("Configuration from event", config);
assertEqualProperties("Properties match", conf.getProperties(),
config.getProperties());
} finally {
getContext().ungetService(cl.getReference());
}
} finally {
removeConfigurationListener(cl);
}
}
/**
* Tests a configuration listener update event notification from a
* configuration service factory. The event data should match the data that
* originated the event (pid, factorypid...).
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.getPid()
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testUpdateConfigFactoryEvent() throws Exception {
ConfigurationListenerImpl cl = null;
String factorypid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
SynchronizerImpl synchronizer = new SynchronizerImpl();
/* Set up the configuration */
Configuration conf = cm.createFactoryConfiguration(factorypid);
String pid = conf.getPid();
Hashtable props = new Hashtable();
props.put("key", "value1");
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
conf.update(props);
trace("Wait until the ConfigurationListener has gotten"
+ "the config factory update");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType());
assertEquals("Config Factory event pid match", factorypid,
cl.getFactoryPid());
assertNotNull("Config Factory event reference null",
cl.getReference());
ConfigurationAdmin admin = (ConfigurationAdmin) getContext()
.getService(cl.getReference());
try {
assertNotNull("Configuration Admin from event", admin);
Configuration config = admin.getConfiguration(cl.getPid());
assertNotNull("Configuration from event", config);
assertEqualProperties("Properties match", conf.getProperties(),
config.getProperties());
} finally {
getContext().ungetService(cl.getReference());
}
} finally {
removeConfigurationListener(cl);
}
}
/**
* Tests a configuration listener delete event notification from a
* configuration service. The deleted <code>Configuration</code> should be
* empty (<code>ConfigurationAdmin.listConfigurations(null)</code> must not
* contain the deleted <code>Configuration</code>).
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @spec ConfigurationAdmin.listConfigurations(String)
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testDeleteConfigEvent() throws Exception {
ConfigurationListenerImpl cl = null;
String pid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
SynchronizerImpl synchronizer = new SynchronizerImpl();
/* Set up the configuration */
Configuration conf = cm.getConfiguration(pid);
Hashtable props = new Hashtable();
props.put("key", "value1");
trace("Create and register a new ConfigurationListener");
try {
cl = createConfigurationListener(synchronizer, 2);
conf.update(props);
trace("Wait until the ConfigurationListener has gotten the update");
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
conf.delete();
trace("Wait until the ConfigurationListener has gotten the delete");
assertTrue("Delete done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME, 2));
assertEquals("Config event pid match", pid, cl.getPid(2));
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, cl.getType(2));
assertNull("Config Factory event pid null", cl.getFactoryPid(2));
assertNotNull("Config Factory event reference null",
cl.getReference(2));
try {
ConfigurationAdmin admin = (ConfigurationAdmin) getContext()
.getService(cl.getReference(2));
assertNotNull("Configuration Admin from event", admin);
Configuration[] configs = admin
.listConfigurations("(service.pid=" + pid + ")");
assertNull("The configuration exists in CM!", configs);
} finally {
getContext().ungetService(cl.getReference(2));
}
} finally {
removeConfigurationListener(cl);
}
}
/**
* Tests a configuration listener delete event notification from a
* configuration service factory. The deleted <code>Configuration</code>
* should be empty (
* <code>ConfigurationAdmin.listConfigurations(null)</code> must not contain
* the deleted <code>Configuration</code>).
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @spec ConfigurationAdmin.listConfigurations(String)
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testDeleteConfigFactoryEvent() throws Exception {
ConfigurationListenerImpl cl = null;
String factorypid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
SynchronizerImpl synchronizer = new SynchronizerImpl();
/* Set up the configuration */
Configuration conf = cm.createFactoryConfiguration(factorypid);
String pid = conf.getPid();
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
conf.delete();
trace("Wait until the ConfigurationListener has gotten"
+ "the config factory delete");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertEquals("Config event pid match", pid, cl.getPid());
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, cl.getType());
assertEquals("Config Factory event pid match", factorypid,
cl.getFactoryPid());
assertNotNull("Config Factory event reference null",
cl.getReference());
ConfigurationAdmin admin = (ConfigurationAdmin) getContext()
.getService(cl.getReference());
try {
assertNotNull("Configuration Admin from event", admin);
Configuration[] configs = admin
.listConfigurations("(service.factoryPid=" + factorypid
+ ")");
assertNull("The configuration exists in CM!", configs);
} finally {
getContext().ungetService(cl.getReference());
}
} finally {
removeConfigurationListener(cl);
}
}
/**
* Tests a configuration listener permission. The bundle does not have
* <code>ServicePermission[ConfigurationListener,REGISTER]</code> and will
* try to register a <code>ConfigurationListener</code>. An exception must
* be thrown.
*
* @spec BundleContext.installBundle(String)
* @spec Bundle.start()
*
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testConfigListenerPermission() throws Exception {
Bundle tb = getContext().installBundle(getWebServer() + "tb1.jar");
String message = "registering config listener without permission";
try {
tb.start();
/* A BundleException should have been thrown if security is enabled */
if (System.getSecurityManager() != null)
failException(message, BundleException.class);
} catch (BundleException e) {
/* Check that we got the correct exception */
assertException(message, BundleException.class, e);
/*
* A BundleException should not have been thrown if security is not
* enabled
*/
if (System.getSecurityManager() == null)
fail("Security is not enabled", e);
} finally {
tb.uninstall();
}
}
/**
* Tests an event from a different bundle. The
* <code>ConfigurationListener</code> should get the event even if it was
* generated from a different bundle.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.getPid()
* @spec Configuration.delete()
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec ConfigurationEvent.getPid()
* @spec ConfigurationEvent.getFactoryPid()
* @spec ConfigurationEvent.getReference()
* @spec ConfigurationEvent.getType()
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testConfigEventFromDifferentBundle() throws Exception {
trace("Create and register a new ConfigurationListener");
SynchronizerImpl synchronizer = new SynchronizerImpl();
ConfigurationListenerImpl cl = createConfigurationListener(
synchronizer, 4);
Bundle tb = getContext().installBundle(getWebServer() + "tb2.jar");
tb.start();
trace("Wait until the ConfigurationListener has gotten the update");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertEquals("Config event pid match", PACKAGE + ".tb2pid."
+ ConfigurationListenerImpl.LISTENER_PID_SUFFIX,
cl.getPid(1));
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType(1));
assertNull("Config Factory event pid null", cl.getFactoryPid(1));
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME, 2));
assertEquals("Config event pid match", PACKAGE + ".tb2pid."
+ ConfigurationListenerImpl.LISTENER_PID_SUFFIX,
cl.getPid(2));
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, cl.getType(2));
assertNull("Config Factory event pid null", cl.getFactoryPid(2));
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME, 3));
assertEquals("Config event facotory pid match", PACKAGE
+ ".tb2factorypid."
+ ConfigurationListenerImpl.LISTENER_PID_SUFFIX,
cl.getFactoryPid(3));
assertEquals("Config event type match",
ConfigurationEvent.CM_UPDATED, cl.getType(3));
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME, 4));
assertEquals("Config event factory pid match", PACKAGE
+ ".tb2factorypid."
+ ConfigurationListenerImpl.LISTENER_PID_SUFFIX,
cl.getFactoryPid(4));
assertEquals("Config event type match",
ConfigurationEvent.CM_DELETED, cl.getType(4));
} finally {
removeConfigurationListener(cl);
tb.uninstall();
}
}
/**
* Tests if a configuration plugin is invoked when only a configuration
* listener is registered (no managed service). It should not be invoked.
*
* @spec ConfigurationAdmin.getConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec
* ConfigurationPlugin.modifyConfiguration(ServiceReference,Dictionary)
*
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testConfigurationPluginService() throws Exception {
ConfigurationListenerImpl cl = null;
NotVisitablePlugin plugin = null;
String pid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
/* Set up the configuration */
Configuration conf = cm.getConfiguration(pid);
Hashtable props = new Hashtable();
props.put("key", "value1");
SynchronizerImpl synchronizer = new SynchronizerImpl();
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
trace("Create and register a new ConfigurationPlugin");
plugin = createConfigurationPlugin();
conf.update(props);
trace("Wait until the ConfigurationListener has gotten the update");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertTrue("ConfigurationPlugin not visited", plugin.notVisited());
} finally {
removeConfigurationListener(cl);
removeConfigurationPlugin(plugin);
}
}
/**
* Tests if a configuration plugin is invoked when only a configuration
* listener is registered (managed service factory). It should not be
* invoked.
*
* @spec ConfigurationAdmin.createFactoryConfiguration(String)
* @spec Configuration.update(Dictionary)
* @spec ConfigurationListener.configurationEvent(ConfigurationEvent)
* @spec
* ConfigurationPlugin.modifyConfiguration(ServiceReference,Dictionary)
*
* @throws Exception
* if an error occurs or an assertion fails in the test.
*/
public void testConfigurationPluginServiceFactory() throws Exception {
ConfigurationListenerImpl cl = null;
NotVisitablePlugin plugin = null;
String factorypid = Util
.createPid(ConfigurationListenerImpl.LISTENER_PID_SUFFIX);
/* Set up the configuration */
Configuration conf = cm.createFactoryConfiguration(factorypid);
Hashtable props = new Hashtable();
props.put("key", "value1");
SynchronizerImpl synchronizer = new SynchronizerImpl();
trace("Create and register a new ConfigurationListener");
cl = createConfigurationListener(synchronizer);
trace("Create and register a new ConfigurationPlugin");
plugin = createConfigurationPlugin();
conf.update(props);
trace("Wait until the ConfigurationListener has gotten the update");
try {
assertTrue("Update done",
synchronizer.waitForSignal(SIGNAL_WAITING_TIME));
assertTrue("ConfigurationPlugin not visited", plugin.notVisited());
} finally {
removeConfigurationListener(cl);
removeConfigurationPlugin(plugin);
}
}
/** *** Helper methods **** */
/**
* creates and registers a configuration listener that expects just one
* event.
*/
private ConfigurationListenerImpl createConfigurationListener(
SynchronizerImpl synchronizer) throws Exception {
return createConfigurationListener(synchronizer, 1);
}
/**
* creates and registers a configuration listener that expects eventCount
* events.
*/
private ConfigurationListenerImpl createConfigurationListener(
SynchronizerImpl synchronizer, int eventCount) throws Exception {
ConfigurationListenerImpl listener = new ConfigurationListenerImpl(
synchronizer, eventCount);
registerService(ConfigurationListener.class.getName(), listener, null);
return listener;
}
/**
* creates and registers a configuration plugin.
*/
private NotVisitablePlugin createConfigurationPlugin() throws Exception {
NotVisitablePlugin plugin = new NotVisitablePlugin();
registerService(ConfigurationPlugin.class.getName(), plugin, null);
return plugin;
}
/**
* unregisters a configuration listener.
*/
private void removeConfigurationListener(ConfigurationListener cl)
throws Exception {
unregisterService(cl);
}
/**
* unregisters a configuration plugin.
*/
private void removeConfigurationPlugin(ConfigurationPlugin plugin)
throws Exception {
unregisterService(plugin);
}
private ManagedServiceImpl createManagedService(String pid, Semaphore s)
throws Exception {
ManagedServiceImpl ms = new ManagedServiceImpl(s);
Hashtable props = new Hashtable();
props.put(Constants.SERVICE_PID, pid);
/* TODO: Testa registered service.pid with other String */
registerService(ManagedService.class.getName(), ms, props);
trace("ManagedService is registered with pid:" + pid);
return ms;
}
private void checkConfiguration(Configuration conf, String message,
String pid, String location) throws BundleException {
assertNotNull(message, conf);
assertEquals("Pid", pid, conf.getPid());
assertNull("FactoryPid", conf.getFactoryPid());
assertNull("Properties", conf.getProperties());
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
}
/**
* See if a configuration is part of a list.
*
* @return index of the list if the configuration is a part of the
* list.Otherwise, return -1nd.
*/
private int isPartOf(Configuration theConf, List configs) {
for (int i = 0; i < configs.size(); i++)
if (equals((Configuration) configs.get(i), theConf))
return i;
return -1;
}
/**
* Compares two Configurations for equality. Configuration.equals() is not
* specified in the spec, so this is a helper method that compares pids.
* <p>
* Two Configurations are considered equal if the got the same pid or if
* both are null.
*/
private boolean equals(Configuration c1, Configuration c2) {
boolean result = false;
/* If both are null, they are equal */
if ((c1 == null) && (c2 == null)) {
result = true;
}
/* If none of them is null, and got the same pid, they are equal */
if ((c1 != null) && (c2 != null)) {
result = c1.getPid().equals(c2.getPid());
}
return result;
}
public final static String PACKAGE = "org.osgi.test.cases.cm.tbc";
private String getLocation() {
return getContext().getBundle().getLocation();
}
/**
* Removes any configurations made by this bundle.
*/
private void cleanCM(Set existingConfigs) throws Exception {
if (cm != null) {
Configuration[] configs = cm.listConfigurations(null);
if (configs != null) {
// log(" cleanCM() -- Checking " + configs.length + " configs");
for (int i = 0; i < configs.length; i++) {
Configuration config = configs[i];
if (!existingConfigs.contains(config.getPid())) {
// log(" Delete " + config.getPid());
config.delete();
} else {
// log(" Keep " + config.getPid());
}
}
} else {
// log(" cleanCM() -- No Configurations to clear");
}
} else {
// log(" cleanCM() -- No CM !");
}
}
class Plugin implements ConfigurationPlugin {
private int index;
Plugin(int x) {
index = x;
}
public void modifyConfiguration(ServiceReference ref, Dictionary props) {
trace("Calling plugin with cmRanking=" + (index * 10));
String[] types = (String[]) ref.getProperty("objectClass");
for (int i = 0; i < types.length; i++) {
if ("org.osgi.service.cm.ManagedService".equals(types[i])) {
props.put("plugin.ms." + index, "added by plugin#" + index);
break;
} else if ("org.osgi.service.cm.ManagedServiceFactory"
.equals(types[i])) {
props.put("plugin.factory." + index, "added by plugin#"
+ index);
break;
}
}
}
}
/**
* <code>ConfigurationPlugin</code> implementation to be used in the
* <code>ConfigurationListener</code> test. The plugin should NOT be invoked
* when there's no <code>ManagedService</code> or
* <code>ManagedServiceFactory</code> registered.
*/
class NotVisitablePlugin implements ConfigurationPlugin {
private boolean visited;
/**
* Creates a <code>ConfigurationPlugin</code> instance that has not been
* invoked (visited) by a <code>Configuration</code> update event.
*
*/
public NotVisitablePlugin() {
visited = false;
}
/**
* <p>
* Callback method when a <code>Configuration</code> update is being
* delivered to a registered <code>ManagedService</code> or
* <code>ManagedServiceFactory</code> instance.
* </p>
* <p>
* Set plugin to visited (<code>visited = true</code>) when this method
* is invoked. If this happens, the <code>ConfigurationListener</code>
* tests failed.
* </p>
*
* @param ref
* the <code>ConfigurationAdmin</code> that generated the
* update.
* @param props
* the <code>Dictionary</code> containing the properties of
* the <code>
* @see org.osgi.service.cm.ConfigurationPlugin#modifyConfiguration(org.osgi.framework.ServiceReference,
* java.util.Dictionary)
*/
public void modifyConfiguration(ServiceReference ref, Dictionary props) {
visited = true;
}
/**
* Checks if the plugin has not been invoked by a <code>Configuration
* </code> update event.
*
* @return <code>true</code> if plugin has not been visited (invoked).
* <code>false</code>, otherwise.
*/
public boolean notVisited() {
return !visited;
}
}
/**
* <code>ConfigurationPlugin</code> implementation to be used in the
* <code>ConfigurationListener</code> test. The plugin should NOT be invoked
* when there's no <code>ManagedService</code> or
* <code>ManagedServiceFactory</code> registered.
*/
class RunnableImpl implements Runnable {
private final String pid;
private String location;
private Configuration conf;
private Object lock = new Object();
RunnableImpl(String pid, String location) {
this.pid = pid;
this.location = location;
}
Configuration getConfiguration() {
return conf;
}
public void run() {
try {
Sleep.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conf = cm.getConfiguration(pid, location);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Sleep.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conf.setBundleLocation(location);
}
void unlock() {
synchronized (lock) {
lock.notifyAll();
}
}
void unlock(String newLocation) {
location = newLocation;
synchronized (lock) {
lock.notifyAll();
}
}
}
class SyncEventListener implements SynchronousConfigurationListener {
private final Synchronizer sync;
public SyncEventListener(final Synchronizer sync) {
this.sync = sync;
}
public void configurationEvent(ConfigurationEvent event) {
this.sync.signal();
}
}
/*
* Shigekuni KONDO, Ikuo YAMASAKI, (Yushi Kuroda), NTT Corporation adds
* tests for specification version 1.4
*/
private final String locationA = "location.a";
private final String locationB = "location.b";
private final String regionA = "?RegionA";
private String regionB = "?RegionB";
public void testGetConfigurationWithLocation_2_01() throws Exception {
final String locationOld = null;
this.internalGetConfigurationWithLocation_2_02To08(1, locationOld);
}
public void testGetConfigurationWithLocation_2_02() throws Exception {
final String locationOld = locationA;
this.internalGetConfigurationWithLocation_2_02To08(2, locationOld);
}
public void testGetConfigurationWithLocation_2_03() throws Exception {
final String locationOld = locationA + "*";
this.internalGetConfigurationWithLocation_2_02To08(3, locationOld);
}
public void testGetConfigurationWithLocation_2_04() throws Exception {
final String locationOld = locationB;
this.internalGetConfigurationWithLocation_2_02To08(4, locationOld);
}
public void testGetConfigurationWithLocation_2_06() throws Exception {
final String locationOld = "?*";
this.internalGetConfigurationWithLocation_2_02To08(6, locationOld);
}
public void testGetConfigurationWithLocation_2_07() throws Exception {
final String locationOld = regionA;
this.internalGetConfigurationWithLocation_2_02To08(7, locationOld);
}
public void testGetConfigurationWithLocation_2_08() throws Exception {
final String locationOld = regionB;
this.internalGetConfigurationWithLocation_2_02To08(8, locationOld);
}
public void internalGetConfigurationWithLocation_2_02To08(final int minor,
final String locationOld) throws BundleException, IOException {
final String header = "testGetConfigurationWithLocation_2_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
this.setAppropriatePermission();
final String pid1 = Util.createPid("1");
Configuration conf = null;
Dictionary props = new Hashtable();
// Get a brand new configuration
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// micro 2
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// micro 1
testId = traceTestId(header, ++micro);
props.put("StringKey", "stringvalue");
conf.update(props);
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// micro 4
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 2) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
// micro 3
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 2) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
// micro 8
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 6 || minor == 7 || minor == 8) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
// micro 7
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 6 || minor == 7 || minor == 8) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
// micro 10
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 7) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
// micro 9
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 7) {
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1,
locationOld);
}
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
// micro 12
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, locationOld);
// micro 11
testId = traceTestId(header, ++micro);
conf.update(props);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, locationOld);
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, locationOld);
// micro 13
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add("?");
cList.add(regionA);
setCPListtoBundle(cList, null, thisBundle);
conf.update(props);
if (minor == 7) {
conf = cm.getConfiguration(pid1, "?");
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, "?");
}
conf.delete();
if (minor == 2) {
resetPermissions();
conf = cm.getConfiguration(pid1, thisLocation);
// micro 16
testId = traceTestId(header, ++micro);
setCPtoBundle(null, null, thisBundle);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// micro 15
testId = traceTestId(header, ++micro);
conf.update(props);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
assertEquals("Check Configuration props", "stringvalue", conf
.getProperties().get("StringKey"));
conf.delete();
}
}
// TODO confirm
public void testGetConfigurationWithLocation_2_09() throws Exception {
final String locationOld = null;
this.internalGetConfigurationWithLocation_2_09To13(9, locationOld);
}
public void testGetConfigurationWithLocation_2_10() throws Exception {
final String locationOld = locationA;
this.internalGetConfigurationWithLocation_2_09To13(10, locationOld);
}
public void testGetConfigurationWithLocation_2_12() throws Exception {
final String locationOld = regionA;
this.internalGetConfigurationWithLocation_2_09To13(12, locationOld);
}
public void testGetConfigurationWithLocation_2_13() throws Exception {
final String locationOld = regionA + "*";
this.internalGetConfigurationWithLocation_2_09To13(13, locationOld);
}
public void internalGetConfigurationWithLocation_2_09To13(final int minor,
final String location) throws BundleException, IOException {
final String header = "testGetConfigurationWithLocation_2_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
this.setAppropriatePermission();
final String pid1 = Util.createPid("1");
Configuration conf = null;
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf = cm.getConfiguration(pid1, location);
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 10) {
conf = cm.getConfiguration(pid1, location);
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
}
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle(locationB, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("?", ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
// 5
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 12 || minor == 13) {
conf = cm.getConfiguration(pid1, location);
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
}
// 6
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 12) {
conf = cm.getConfiguration(pid1, location);
assertEquals("Location", location,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
} else {
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
}
// 7
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbyGetConfigurationWithLocation(testId, pid1, location);
if (minor == 10) {
// thisLocation no permission
testId = traceTestId(header, ++micro);
setCPtoBundle(null, null, thisBundle);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
// thisLocation with CONFIGURE
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE,
thisBundle);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
// thisLocation with TARGET
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
conf = cm.getConfiguration(pid1, thisLocation);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
conf.delete();
}
}
private void setCPtoBundle(String name, String action, Bundle bundle)
throws BundleException {
this.setCPtoBundle(name, action, bundle, true);
}
private void setCPtoBundle(String name, String action, Bundle bundle,
boolean resetAll) throws BundleException {
if (resetAll)
this.resetPermissions();
list.clear();
add(list, PropertyPermission.class.getName(), "*", "READ,WRITE");
add(list, PP, "*", "IMPORT,EXPORTONLY");
add(list, SP, "*", "GET,REGISTER");
if (name != null && action != null)
add(list, CP, name, action);
add(list, AP, "*", "*");
permissionFlag = true;
this.setBundlePermission(bundle, list);
}
private void resetBundlePermission(Bundle b, List list) throws BundleException {
this.resetPermissions();
if (list != null) {
this.setBundlePermission(b, list);
}
}
private String traceTestId(final String header, int micro) {
String testId = header + String.valueOf(micro);
trace(testId);
return testId;
}
private void assertThrowsSEbyGetConfigurationWithLocation(String testId,
String pid, String location) {
String message = testId
+ ":try to get configuration without appropriate ConfigurationPermission.";
try {
cm.getConfiguration(pid, location);
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
public void testGetConfiguration_3_01() throws Exception {
final String locationOld = null;
this.internalGetConfiguration_3_01To07(1, locationOld);
}
public void testGetConfiguration_3_02() throws Exception {
final String locationOld = locationA;
this.internalGetConfiguration_3_01To07(2, locationOld);
}
public void testGetConfiguration_3_03() throws Exception {
final String locationOld = locationA + "*";
this.internalGetConfiguration_3_01To07(3, locationOld);
}
public void testGetConfiguration_3_04() throws Exception {
final String locationOld = locationB;
this.internalGetConfiguration_3_01To07(4, locationOld);
}
public void testGetConfiguration_3_06() throws Exception {
final String locationOld = regionA;
this.internalGetConfiguration_3_01To07(6, locationOld);
}
public void testGetConfiguration_3_07() throws Exception {
final String locationOld = regionA + "*";
this.internalGetConfiguration_3_01To07(7, locationOld);
}
public void internalGetConfiguration_3_01To07(int minor, String locationOld)
throws BundleException, IOException {
final String header = "testGetConfiguration_3_" + String.valueOf(minor)
+ "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
Dictionary props = new Hashtable();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
String message = testId
+ ":try to get configuration with appropriate ConfigurationPermission.";
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf = cm.getConfiguration(pid1);
if (minor == 1) {
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
}
// 1
testId = traceTestId(header, ++micro);
props.put("StringKey", "stringvalue");
conf.update(props);
conf = cm.getConfiguration(pid1);
if (minor == 1) {
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
}
conf.delete();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else if (minor == 2) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
// 3
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else if (minor == 2) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
conf.delete();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 8
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else if (minor == 6 || minor == 7) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
// 7
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else if (minor == 6 || minor == 7) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
conf.delete();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 10
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else if (minor == 6) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
// 9
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else if (minor == 6) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", locationOld,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
conf.delete();
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 12
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
// 11
testId = traceTestId(header, ++micro);
conf.update(props);
if (minor == 1) {
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
} else {
assertThrowsSEbyGetConfiguration(pid1, message);
}
conf.delete();
if (minor == 1) {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 15
testId = traceTestId(header, ++micro);
setCPtoBundle(null, null, thisBundle);
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// 14
testId = traceTestId(header, ++micro);
conf.update(props);
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisBundle.getLocation(),
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
conf.delete();
}
if (minor == 2) {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, thisLocation);
// 15
testId = traceTestId(header, ++micro);
setCPtoBundle(null, null, thisBundle);
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertNull("Configuration props MUST be null", conf.getProperties());
// 14
testId = traceTestId(header, ++micro);
conf.update(props);
conf = cm.getConfiguration(pid1);
assertEquals("Location", thisLocation,
this.getBundleLocationForCompare(conf));
assertEquals("Check Configuration props", 2, conf.getProperties()
.size());
conf.delete();
}
}
private void assertThrowsSEbyGetConfiguration(final String pid,
String message) throws AssertionFailedError {
try {
cm.getConfiguration(pid);
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
// TODO confirm
public void testCreateFactoryConfiguration_4_01() throws Exception {
String location = null;
this.internalCreateFactoryConfigurationWithLocation_4_01To07(1,
location);
}
public void testCreateFactoryConfiguration_4_02() throws Exception {
String location = locationA;
this.internalCreateFactoryConfigurationWithLocation_4_01To07(2,
location);
}
public void testCreateFactoryConfiguration_4_03() throws Exception {
String location = locationA + "*";
this.internalCreateFactoryConfigurationWithLocation_4_01To07(3,
location);
}
public void testCreateFactoryConfiguration_4_04() throws Exception {
String location = locationB;
this.internalCreateFactoryConfigurationWithLocation_4_01To07(4,
location);
}
public void testCreateFactoryConfiguration_4_06() throws Exception {
String location = regionA;
this.internalCreateFactoryConfigurationWithLocation_4_01To07(6,
location);
}
public void testCreateFactoryConfiguration_4_07() throws Exception {
String location = regionA + "*";
this.internalCreateFactoryConfigurationWithLocation_4_01To07(7,
location);
}
public void internalCreateFactoryConfigurationWithLocation_4_01To07(
int minor, String location) throws BundleException, IOException {
final String header = "testCreateFactoryConfigurationWithLocation_4_"
+ String.valueOf(minor) + "_";
;
String fpid = Util.createPid("factory1");
String testId = null;
int micro = 0;
String message = testId
+ ":try to create factory configuration with location with inappropriate ConfigurationPermission.";
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
Configuration conf1 = cm.createFactoryConfiguration(fpid, location);
Configuration conf2 = cm.createFactoryConfiguration(fpid, location);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf2));
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 2) {
conf1 = cm.createFactoryConfiguration(fpid, location);
conf2 = cm.createFactoryConfiguration(fpid, location);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf2));
} else {
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
}
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 6 || minor == 7) {
conf1 = cm.createFactoryConfiguration(fpid, location);
conf2 = cm.createFactoryConfiguration(fpid, location);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf2));
} else {
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
}
// 5
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 6) {
conf1 = cm.createFactoryConfiguration(fpid, location);
conf2 = cm.createFactoryConfiguration(fpid, location);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", location,
this.getBundleLocationForCompare(conf2));
} else {
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
}
// 6
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
// 7
if (minor == 6) {
testId = traceTestId(header, ++micro);
setCPtoBundle(regionB, ConfigurationPermission.CONFIGURE,
thisBundle);
this.assertThrowsSEbyCreateFactoryConf(fpid, location, message);
}
// 8
if (minor == 2) {
traceTestId(header, ++micro);
this.resetPermissions();
setCPtoBundle(null, null, thisBundle);
conf1 = cm.createFactoryConfiguration(fpid, thisLocation);
conf2 = cm.createFactoryConfiguration(fpid, thisLocation);
assertEquals("Check conf fpid.", conf1.getFactoryPid(),
conf2.getFactoryPid());
assertFalse("Check conf pid does not same.",
conf1.getPid().equals(conf2.getPid()));
assertEquals("Check conf location.", thisLocation,
this.getBundleLocationForCompare(conf1));
assertEquals("Check conf location.", thisLocation,
this.getBundleLocationForCompare(conf2));
}
}
private void assertThrowsSEbyCreateFactoryConf(final String fPid,
final String location, String message) throws AssertionFailedError {
try {
cm.createFactoryConfiguration(fPid, location);
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
public void testListConfigurations_6_01() throws Exception {
String filter = null;
this.internalListConfigurations(1, filter);
}
public void testListConfigurations_6_02() throws Exception {
String filter = "(service.pid=pid1)";
this.internalListConfigurations(2, filter);
}
public void testListConfigurations_6_03() throws Exception {
String filter = "(service.bundleLocation=location.a)";
this.internalListConfigurations(3, filter);
}
public void testListConfigurations_6_04() throws Exception {
String filter = "(service.bundleLocation=?RegionA)";
this.internalListConfigurations(4, filter);
}
public void testListConfigurations_6_05() throws Exception {
String filter = "(&(service.bundleLocation=?RegionA)(service.pid=pid2))";
this.internalListConfigurations(5, filter);
}
public void internalListConfigurations(int minor, String filter)
throws IOException, InvalidSyntaxException, BundleException {
final String header = "testListConfigurations_6_"
+ String.valueOf(minor) + "_";
int micro = 0;
String testId = null;
String pid1 = "pid1";
String pid2 = "pid2";
String pid3 = "pid3";
Configuration conf1 = null;
Configuration conf2 = null;
Configuration conf3 = null;
Dictionary prop = new Hashtable();
prop.put("StringKey", "Stringvalue");
String message = testId + ":try listConfigurations ";
this.setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf1 = cm.getConfiguration(pid1, locationA);
conf1.update(prop);
conf2 = cm.getConfiguration(pid2, regionA);
conf2.update(prop);
conf3 = cm.getConfiguration(pid3, "?");
conf3.update(prop);
testId = traceTestId(header, ++micro);
this.setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE,
thisBundle);
Configuration[] conflist = cm.listConfigurations(filter);
if (minor == 4 || minor == 5) {
assertNull("Returned list of configuration MUST be null.", conflist);
} else {
assertEquals("number of Configuration Object", 1, conflist.length);
assertEquals(message, conflist[0], conf1);
}
testId = traceTestId(header, ++micro);
this.setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE,
thisBundle);
conflist = cm.listConfigurations(filter);
if (minor == 1 || minor == 4 || minor == 5) {
assertEquals("number of Configuration Object", 1, conflist.length);
assertEquals(message, conflist[0], conf2);
} else {
assertNull("Returned list of configuration MUST be null.", conflist);
}
}
// TODO
public void testGetBundleLocation_7_01() throws Exception {
String locationOld = null;
this.internalGetBundleLocation_7_01to08(1, locationOld);
}
public void testGetBundleLocation_7_02() throws Exception {
String locationOld = locationA;
this.internalGetBundleLocation_7_01to08(2, locationOld);
}
public void testGetBundleLocation_7_03() throws Exception {
String locationOld = locationA + "*";
this.internalGetBundleLocation_7_01to08(3, locationOld);
}
public void testGetBundleLocation_7_05() throws Exception {
String locationOld = "?*";
this.internalGetBundleLocation_7_01to08(5, locationOld);
}
public void testGetBundleLocation_7_06() throws Exception {
String locationOld = regionA;
this.internalGetBundleLocation_7_01to08(6, locationOld);
}
public void testGetBundleLocation_7_07() throws Exception {
String locationOld = regionA + "*";
this.internalGetBundleLocation_7_01to08(7, locationOld);
}
public void testGetBundleLocation_7_08() throws Exception {
String locationOld = thisLocation;
this.internalGetBundleLocation_7_01to08(8, locationOld);
}
public void internalGetBundleLocation_7_01to08(final int minor,
final String locationOld) throws Exception {
final String header = "testGetBundleLocation_7_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
String loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE,
thisBundle);
if (minor == 2) {
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
} else {
this.assertThrowsSEbyGetLocation(conf, testId);
}
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("?", ConfigurationPermission.CONFIGURE, thisBundle);
this.assertThrowsSEbyGetLocation(conf, testId);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
if (minor == 5 || minor == 6 || minor == 7) {
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
} else {
this.assertThrowsSEbyGetLocation(conf, testId);
}
// 5
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE,
thisBundle);
if (minor == 6) {
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
} else {
this.assertThrowsSEbyGetLocation(conf, testId);
}
// 6
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
this.assertThrowsSEbyGetLocation(conf, testId);
// 7
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE + ","
+ ConfigurationPermission.TARGET, thisBundle);
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
// 8
if (minor == 6 || minor == 7) {
testId = traceTestId(header, ++micro);
setCPtoBundle(regionB, ConfigurationPermission.CONFIGURE,
thisBundle);
this.assertThrowsSEbyGetLocation(conf, testId);
}
++micro;
// 9
if (minor == 6) {
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE + ","
+ ConfigurationPermission.TARGET, thisBundle);
loc = conf.getBundleLocation();
assertEquals("Check conf location", locationOld, loc);
}
++micro;
// 10
testId = traceTestId(header, ++micro);
conf.delete();
resetPermissions();
conf = cm.getConfiguration(pid1, thisLocation);
// Bug2539: need to have CONFIGURE(thisLocation)
setCPtoBundle(thisLocation, ConfigurationPermission.CONFIGURE, thisBundle);
loc = conf.getBundleLocation();
assertEquals("Check conf location", thisLocation, loc);
} finally {
this.resetPermissions();
if (conf != null)
conf.delete();
}
}
private void assertThrowsSEbyGetLocation(final Configuration conf,
String testId) throws AssertionFailedError {
String message = testId
+ ":try to get bundle location without appropriate ConfigurationPermission.";
try {
conf.getBundleLocation();
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
public void testSetBundleLocation_8_01() throws Exception {
String locationOld = null;
String location = null;
this.internalSetBundleLocation_8_01to07(1, locationOld, location);
}
public void testSetBundleLocation_8_02() throws Exception {
String locationOld = null;
String location = locationA;
this.internalSetBundleLocation_8_01to07(2, locationOld, location);
}
public void testSetBundleLocation_8_04() throws Exception {
String locationOld = null;
String location = "?*";
this.internalSetBundleLocation_8_01to07(4, locationOld, location);
}
public void testSetBundleLocation_8_05() throws Exception {
String locationOld = null;
String location = regionA;
this.internalSetBundleLocation_8_01to07(5, locationOld, location);
}
public void testSetBundleLocation_8_06() throws Exception {
String locationOld = locationA;
String location = null;
this.internalSetBundleLocation_8_01to07(6, locationOld, location);
}
public void testSetBundleLocation_8_07() throws Exception {
String locationOld = locationA;
String location = locationA;
this.internalSetBundleLocation_8_01to07(7, locationOld, location);
}
public void internalSetBundleLocation_8_01to07(final int minor,
final String locationOld, final String location) throws Exception {
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 2
testId = traceTestId(header, ++micro);
if (minor == 6 || minor == 7) {
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE,
thisBundle);
if (minor == 7) {
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
} else
assertThrowsSEbySetLocation(conf, location, testId);
} else {
setCPtoBundle("?*", ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
}
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_08() throws Exception {
int minor = 8;
String locationOld = locationA;
String location = locationB;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add(locationA);
cList.add(locationB);
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle(locationB, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(locationOld);
// 5
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_10() throws Exception {
int minor = 10;
String locationOld = locationA;
String location = regionA;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add(locationA);
cList.add(regionA);
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_15() throws Exception {
int minor = 15;
String locationOld = regionA;
String location = null;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_16() throws Exception {
int minor = 16;
String locationOld = regionA;
String location = locationA;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add(locationA);
cList.add(regionA);
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle(locationA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_17() throws Exception {
int minor = 17;
String locationOld = regionA;
String location = "?";
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add("?");
cList.add(regionA);
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("?", ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
this.setAppropriatePermission();
conf.setBundleLocation(locationOld);
// 4
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_18() throws Exception {
int minor = 18;
String locationOld = regionA;
String location = regionA;
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
setCPtoBundle(regionA, ConfigurationPermission.CONFIGURE, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
// 2
testId = traceTestId(header, ++micro);
setCPtoBundle("?", ConfigurationPermission.CONFIGURE, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
public void testSetBundleLocation_8_19() throws Exception {
int minor = 19;
String locationOld = locationA + "*";
String location = regionA + "*";
final String header = "testSetBundleLocation_8_"
+ String.valueOf(minor) + "_";
String testId = null;
int micro = 0;
final String pid1 = Util.createPid("1");
Configuration conf = null;
try {
this.setAppropriatePermission();
conf = cm.getConfiguration(pid1, locationOld);
assertEquals("Check Conf location.", locationOld,
this.getBundleLocationForCompare(conf));
// 1
testId = traceTestId(header, ++micro);
List cList = new ArrayList();
cList.add(locationA + "*");
cList.add(regionA + "*");
setCPListtoBundle(cList, null, thisBundle);
conf.setBundleLocation(location);
assertEquals("Check Conf location.", location,
this.getBundleLocationForCompare(conf));
// 2
testId = traceTestId(header, ++micro);
cList = new ArrayList();
cList.add(locationA + ".com");
cList.add(regionA + ".com");
setCPListtoBundle(cList, null, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
// 3
testId = traceTestId(header, ++micro);
setCPtoBundle("*", ConfigurationPermission.TARGET, thisBundle);
assertThrowsSEbySetLocation(conf, location, testId);
} finally {
if (conf != null) {
conf.delete();
}
}
}
private void setCPListtoBundle(List nameforConfigure, List nameForTarget,
Bundle bundle) throws BundleException {
this.resetPermissions();
list.clear();
add(list, PropertyPermission.class.getName(), "*", "READ,WRITE");
add(list, PP, "*", "IMPORT,EXPORTONLY");
add(list, SP, "*", "GET,REGISTER");
add(list, AP, "*", "*");
if (nameforConfigure != null)
if (!nameforConfigure.isEmpty()) {
for (Iterator itc = nameforConfigure.iterator(); itc.hasNext();) {
add(list, CP, (String) itc.next(),
ConfigurationPermission.CONFIGURE);
}
}
if (nameForTarget != null)
if (!nameForTarget.isEmpty()) {
for (Iterator itt = nameforConfigure.iterator(); itt.hasNext();) {
add(list, CP, (String) itt.next(),
ConfigurationPermission.TARGET);
}
}
permissionFlag = true;
this.setBundlePermission(bundle, list);
}
private void assertThrowsSEbySetLocation(final Configuration conf,
final String location, String testId) throws AssertionFailedError {
String message = testId
+ ":try to set bundle location without appropriate ConfigurationPermission.";
try {
conf.setBundleLocation(location);
// A SecurityException should have been thrown
failException(message, SecurityException.class);
} catch (AssertionFailedError e) {
throw e;
} catch (Throwable e) {
// Check that we got the correct exception
assertException(message, SecurityException.class, e);
}
}
/* Ikuo YAMASAKI */
private int assertCallback(SynchronizerImpl sync, int count) {
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count);
assertTrue(
"ManagedService#updated(props)/ManagedServiceFactory#updated(pid,props) must be called back",
calledback);
return count;
}
private void assertNoCallback(SynchronizerImpl sync, int count) {
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1);
assertFalse(
"ManagedService#updated(props)/ManagedServiceFactory#updated(pid,props) must NOT be called back",
calledback);
}
private int assertDeletedCallback(SynchronizerImpl sync, int count) {
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, ++count,
true);
assertTrue("ManagedServiceFactory#deleted(pid) must be called back",
calledback);
return count;
}
private void assertDeletedNoCallback(SynchronizerImpl sync, int count) {
boolean calledback = sync.waitForSignal(SIGNAL_WAITING_TIME, count + 1,
true);
assertFalse(
"ManagedServiceFactory#deleted(pid) must NOT be called back",
calledback);
}
private void cleanUpForCallbackTest(final Bundle bundleT1,
final Bundle bundleT2, final Bundle bundleT3, List list)
throws BundleException {
this.cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, null, list);
}
private void cleanUpForCallbackTest(final Bundle bundleT1,
final Bundle bundleT2, final Bundle bundleT3,
final Bundle bundleT4, List list) throws BundleException {
for (Iterator regs = list.iterator(); regs.hasNext();)
((ServiceRegistration) regs.next()).unregister();
list.clear();
if (bundleT1 != null)
bundleT1.uninstall();
if (bundleT2 != null)
bundleT2.uninstall();
if (bundleT3 != null)
bundleT3.uninstall();
if (bundleT4 != null)
bundleT4.uninstall();
}
/**
*
* @throws Exception
*/
public void testManagedServiceRegistration9_1_1() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(3);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testSetBundleLocation_9_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.setCPtoBundle(null, null, bundleT1, false);
this.startTargetBundle(bundleT1);
// this.setInappropriatePermission();
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
this.setAppropriatePermission();
Configuration conf = cm.getConfiguration(pid1,
bundleT1.getLocation());
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_1);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("Conf is being deleted.");
conf.delete();
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
private void restartCM() throws BundleException {
Bundle cmBundle = stopCmBundle();
cmBundle.stop();
trace("CM has been stopped.");
startCmBundle(cmBundle);
trace("CM has been started.");
}
/**
*
* @throws Exception
*/
public void testManagedServiceRegistration9_1_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(3);
/*
* A. create Configuration in advance, Then Register ManagedService .
*/
final String header = "testSetBundleLocation_9_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, bundleT1.getLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.setCPtoBundle(null, null, bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("null props must be called back", sync1_1.getProps());
assertEquals("Check props", "stringvalue",
sync1_1.getProps().get("StringKey"));
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("Conf is being deleted.");
conf.delete();
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
/**
*
* @throws Exception
*/
// public void testManagedServiceRegistration9_2_1() throws Exception {
// final Bundle bundleT1 = getContext().installBundle(
// getWebServer() + "bundleT1.jar");
// final Bundle bundleT2 = getContext().installBundle(
// getWebServer() + "bundleT2.jar");
// final String locationT2 = bundleT2.getLocation();
// final String pid1 = Util.createPid("pid1");
// List list = new ArrayList(3);
// /*
// * A. Register ManagedService in advance. Then create Configuration.
// */
// final String header = "testSetBundleLocation_9_2_1";
//
// String testId = null;
// int micro = 0;
// testId = traceTestId(header, ++micro);
//
// this.setCPtoBundle(locationT2, "target", bundleT1);
//
// try {
// SynchronizerImpl sync1_1 = new SynchronizerImpl();
// list.add(getContext().registerService(Synchronizer.class.getName(),
// sync1_1, propsForSync1_1));
// SynchronizerImpl sync1_2 = new SynchronizerImpl();
// list.add(getContext().registerService(Synchronizer.class.getName(),
// sync1_2, propsForSync1_2));
// this.startTargetBundle(bundleT1);
// trace("Wait for signal.");
// int count1_1 = 0;
// count1_1 = assertCallback(sync1_1, count1_1);
// assertNull("called back with null props", sync1_1.getProps());
// int count1_2 = 0;
// count1_2 = assertCallback(sync1_2, count1_2);
// assertNull("called back with null props", sync1_2.getProps());
//
// trace("The configuration is being created");
//
// Configuration conf = cm.getConfiguration(pid1, bundleT2
// .getLocation());
// trace("Wait for signal.");
// assertNoCallback(sync1_1, count1_1);
//
// trace("The configuration is being updated ");
// Dictionary props = new Hashtable();
// props.put("StringKey", "stringvalue");
// conf.update(props);
// trace("Wait for signal.");
// assertNoCallback(sync1_1, count1_1);
// assertNoCallback(sync1_2, count1_2);
//
// // restartCM();
// // conf = cm.getConfiguration(pid1, bundleT2.getLocation());
// // trace("Wait for signal.");
// // count1_1 = assertCallback(sync1_1, count1_1);
// // count1_2 = assertCallback(sync1_2, count1_2);
// // assertNull("called back with null props", sync1_2.getProps());
// //
// // trace("conf is going to be deleted.");
// // conf.delete();
// // count1_1 = assertCallback(sync1_1, count1_1);
// // assertNull("called back with null props", sync1_1.getProps());
// // this.assertNoCallback(sync1_2, count1_2);
//
// } finally {
// this.cleanUpForCallbackTest(bundleT1, null, null, list);
// }
// }
//
public void testManagedServiceRegistration9_2_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
internalManagedServiceRegistration9_2_1to2(2, bundleT2.getLocation(),
ConfigurationPermission.TARGET, bundleT1, bundleT2);
}
public void testManagedServiceRegistration9_2_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
internalManagedServiceRegistration9_2_1to2(3, "*",
ConfigurationPermission.TARGET, bundleT1, bundleT2);
}
private void internalManagedServiceRegistration9_2_1to2(final int micro,
final String target, final String actions, final Bundle bundleT1,
final Bundle bundleT2) throws Exception {
final String locationT2 = bundleT2.getLocation();
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(3);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testSetBundleLocation_9_2_"
+ String.valueOf(micro);
String testId = null;
int micro1 = 0;
testId = traceTestId(header, ++micro1);
this.setCPtoBundle(actions, target, bundleT1);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl();
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1,
bundleT2.getLocation());
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("conf is going to be deleted.");
conf.delete();
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
/**
*
* @throws Exception
*/
public void testManagedServiceRegistration9_2_4() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
internalManagedServiceRegistration9_2_4to5(4, bundleT2.getLocation(),
"target", bundleT1, bundleT2);
}
public void testManagedServiceRegistration9_2_5() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
internalManagedServiceRegistration9_2_4to5(5, "*", "target", bundleT1,
bundleT2);
}
public void internalManagedServiceRegistration9_2_4to5(final int micro,
final String target, final String actions, final Bundle bundleT1,
final Bundle bundleT2) throws Exception {
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(3);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testSetBundleLocation_9_2_"
+ String.valueOf(micro);
int micro1 = 0;
String testId = traceTestId(header, ++micro1);
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, bundleT2.getLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
this.setCPtoBundle(target, actions, bundleT1);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("Conf is being deleted.");
conf.delete();
this.assertNoCallback(sync1_1, count1_1);
this.assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, null, list);
}
}
/**
* Register ManagedService in advance. Then create Configuration.
*
* @throws Exception
*/
public void testManagedServiceRegistrationMultipleTargets_10_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final Bundle bundleT4 = getContext().installBundle(
getWebServer() + "bundleT4.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(7);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testManagedServiceRegistrationMultipleTargets_10_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSync3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSync3_2));
SynchronizerImpl sync4_1 = new SynchronizerImpl("4-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_1, propsForSync4_1));
SynchronizerImpl sync4_2 = new SynchronizerImpl("4-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_2, propsForSync4_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?*", "target", bundleT2, false);
this.setCPtoBundle("?RegionA", "target", bundleT3, false);
this.setCPtoBundle("?RegionA", "target", bundleT4, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
int count3_1 = 0;
count3_1 = assertCallback(sync3_1, count3_1);
assertNull("called back with null props", sync3_1.getProps());
int count3_2 = 0;
count3_2 = assertCallback(sync3_2, count3_2);
assertNull("called back with null props", sync3_2.getProps());
this.startTargetBundle(bundleT4);
// TODO Called back twice each pid.
// int count4_1 = 0;
int count4_1 = 1;
count4_1 = assertCallback(sync4_1, count4_1);
assertNull("called back with null props", sync4_1.getProps());
// count4_1 = 2
// int count4_2 = 0;
int count4_2 = 1;
count4_2 = assertCallback(sync4_2, count4_2);
assertNull("called back with null props", sync4_2.getProps());
// count4_2 = 2
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
assertNoCallback(sync4_1, count4_1);
assertNoCallback(sync4_2, count4_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNotNull("called back with Non-null props", sync2_1.getProps());
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
count4_1 = assertCallback(sync4_1, count4_1);
assertNotNull("called back with Non-null props", sync4_1.getProps());
assertNoCallback(sync4_2, count4_2);
trace("conf is going to be deleted.");
conf.delete();
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
count3_1 = assertCallback(sync3_1, count3_1);
assertNull("called back with null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNull("called back with null props", sync3_2.getProps());
count4_1 = assertCallback(sync4_1, count4_1);
assertNull("called back with null props", sync4_1.getProps());
assertNoCallback(sync4_2, count4_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, bundleT4, list);
}
}
/**
* Register ManagedService in advance. Then create Configuration.
*
* @throws Exception
*/
public void testManagedServiceRegistrationMultipleTargets_10_1_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final Bundle bundleT4 = getContext().installBundle(
getWebServer() + "bundleT4.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testManagedServiceRegistrationMultipleTargets_10_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSync3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSync3_2));
SynchronizerImpl sync4_1 = new SynchronizerImpl("4-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_1, propsForSync4_1));
SynchronizerImpl sync4_2 = new SynchronizerImpl("4-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_2, propsForSync4_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle("?RegionB", "target", bundleT3, false);
this.setCPtoBundle("?RegionA", "target", bundleT4, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
int count3_1 = 0;
count3_1 = assertCallback(sync3_1, count3_1);
assertNull("called back with null props", sync3_1.getProps());
int count3_2 = 0;
count3_2 = assertCallback(sync3_2, count3_2);
assertNull("called back with null props", sync3_2.getProps());
this.startTargetBundle(bundleT4);
// int count4_1 = 0;
int count4_1 = 1;
count4_1 = assertCallback(sync4_1, count4_1);
assertNull("called back with null props", sync4_1.getProps());
// int count4_2 = 0;
int count4_2 = 1;
count4_2 = assertCallback(sync4_2, count4_2);
assertNull("called back with null props", sync4_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
assertNoCallback(sync4_1, count4_1);
assertNoCallback(sync4_2, count4_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
count4_1 = assertCallback(sync4_1, count4_1);
assertNotNull("called back with Non-null props", sync4_1.getProps());
assertNoCallback(sync4_2, count4_2);
trace("conf is going to be deleted.");
conf.delete();
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
count4_1 = assertCallback(sync4_1, count4_1);
assertNull("called back with null props", sync4_1.getProps());
assertNoCallback(sync4_2, count4_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, bundleT4, list);
}
}
public void testManagedServiceRegistrationMultipleTargets_10_2_1()
throws Exception {
System.setProperty("org.osgi.test.cases.cm.bundleT4.mode","Array" );
try {
this.internalTestManagedServiceRegistrationMultipleTargets_10_2_1to3();
} finally {
System.getProperties().remove("org.osgi.test.cases.cm.bundleT4.mode");
}
}
public void testManagedServiceRegistrationMultipleTargets_10_2_2()
throws Exception {
System.setProperty("org.osgi.test.cases.cm.bundleT4.mode", "Vector");
try {
this.internalTestManagedServiceRegistrationMultipleTargets_10_2_1to3();
} finally {
System.getProperties().remove("org.osgi.test.cases.cm.bundleT4.mode");
}
}
public void testManagedServiceRegistrationMultipleTargets_10_2_3()
throws Exception {
System.setProperty("org.osgi.test.cases.cm.bundleT4.mode", "List");
try {
this.internalTestManagedServiceRegistrationMultipleTargets_10_2_1to3();
} finally {
System.getProperties().remove("org.osgi.test.cases.cm.bundleT4.mode");
}
}
private void internalTestManagedServiceRegistrationMultipleTargets_10_2_1to3()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final Bundle bundleT4 = getContext().installBundle(
getWebServer() + "bundleT4.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceRegistrationMultipleTargets_10_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSync3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSync3_2));
SynchronizerImpl sync4_1 = new SynchronizerImpl("4-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_1, propsForSync4_1));
SynchronizerImpl sync4_2 = new SynchronizerImpl("4-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_2, propsForSync4_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?*", "target", bundleT2, false);
this.setCPtoBundle("?RegionA", "target", bundleT3, false);
this.setCPtoBundle("?RegionA", "target", bundleT4, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with NON-null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
int count3_1 = 0;
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with NON-null props", sync3_1.getProps());
int count3_2 = 0;
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with NON-null props", sync3_2.getProps());
this.startTargetBundle(bundleT4);
trace("Wait for signal.");
// MS for pid2, pid1; two callbacks expected
int count4_1 = 0;
count4_1 = assertCallback(sync4_1, count4_1+1);
assertEquals("expect two callbacks", count4_1, 2);
assertNotNull("called back with NON-null props", sync4_1.getProps());
// MS for pid2, pid3; two callbacks expected
int count4_2 = 0;
count4_2 = assertCallback(sync4_2, count4_2+1);
assertEquals("expect two callbacks", count4_2, 2);
assertNull("called back with null props", sync4_2.getProps());
// trace("conf is going to be deleted.");
// conf.delete();
// assertNoCallback(sync1_1, count1_1);
// assertNoCallback(sync1_2, count1_2);
// count2_1 = assertCallback(sync2_1, count2_1);
// assertNull("called back with null props", sync2_1.getProps());
// count3_1 = assertCallback(sync3_1, count3_1);
// assertNull("called back with null props", sync3_1.getProps());
// count3_2 = assertCallback(sync3_2, count3_2);
// assertNull("called back with null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, bundleT4, list);
}
}
public void testManagedServiceRegistrationMultipleTargets_10_2_4()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final Bundle bundleT4 = getContext().installBundle(
getWebServer() + "bundleT4.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testManagedServiceRegistrationMultipleTargets_10_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSync3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSync3_2));
SynchronizerImpl sync4_1 = new SynchronizerImpl("4-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_1, propsForSync4_1));
SynchronizerImpl sync4_2 = new SynchronizerImpl("4-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync4_2, propsForSync4_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle("?RegionB", "target", bundleT3, false);
this.setCPtoBundle("?RegionA", "target", bundleT4, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
trace("Wait for signal.");
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
trace("Wait for signal.");
int count3_1 = 0;
count3_1 = assertCallback(sync3_1, count3_1);
assertNull("called back with null props", sync3_1.getProps());
// assertNotNull("called back with NON-null props",
// sync3_1.getProps());
int count3_2 = 0;
count3_2 = assertCallback(sync3_2, count3_2);
assertNull("called back with null props", sync3_2.getProps());
String mode = System
.getProperty("org.osgi.test.cases.cm.bundleT4.mode");
System.out.println("##########################" + mode);
this.startTargetBundle(bundleT4);
trace("Wait for signal.");
int count4_1 = 0;
count4_1 = assertCallback(sync4_1, count4_1);
// ignore actual call back properties, might already have been overwritten
count4_1 = assertCallback(sync4_1, count4_1);
assertNotNull("called back with NON-null props", sync4_1.getProps());
int count4_2 = 0;
count4_2 = assertCallback(sync4_2, count4_2);
// ignore actual call back properties, might already have been overwritten
count4_2 = assertCallback(sync4_2, count4_2);
assertNull("called back with null props", sync4_2.getProps());
// trace("conf is going to be deleted.");
// conf.delete();
// assertNoCallback(sync1_1, count1_1);
// assertNoCallback(sync1_2, count1_2);
// count2_1 = assertCallback(sync2_1, count2_1);
// assertNull("called back with null props", sync2_1.getProps());
// count3_1 = assertCallback(sync3_1, count3_1);
// assertNull("called back with null props", sync3_1.getProps());
// count3_2 = assertCallback(sync3_2, count3_2);
// assertNull("called back with null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, bundleT4, list);
}
}
public void testManagedServiceRegistrationMultipleTargets_11_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
/*
* A. Register ManagedService in advance. Then create Configuration.
*/
final String header = "testManagedServiceRegistrationMultipleTargets_11_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSync2_1));
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
this.startTargetBundle(bundleT2);
int count2_1 = 0;
count2_1 = assertCallback(sync2_1, count2_1);
assertNull("called back with null props", sync2_1.getProps());
this.printoutPermissions();
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("*", "target", bundleT2, false);
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, null);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
sleep(3000);
if(conf.getBundleLocation().equals(bundleT1.getLocation())){
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props",
sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertEquals("conf.location must be dynamically set to location of T1.",
conf.getBundleLocation(),bundleT1.getLocation());
bundleT1.stop();
bundleT1.uninstall();
props.put("StringKey", "stringvalueNew");
trace("The configuration is being updated ");
conf.update(props);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with NON-null props",sync2_1.getProps());
bundleT2.stop();
bundleT2.uninstall();
}else if(conf.getBundleLocation().equals(bundleT2.getLocation())){
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with NON-null props",
sync2_1.getProps());
assertEquals("conf.location must be dynamically set to location of T2.",
conf.getBundleLocation(),bundleT2.getLocation());
trace("The bound bundleT2 is going to unregister MS.");
bundleT2.stop();
bundleT2.uninstall();
props.put("StringKey", "stringvalueNew");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props",sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
bundleT1.stop();
bundleT1.uninstall();
}else{
fail();
}
} finally {
cleanUpForCallbackTest(null, null, null, list);
}
}
public void testManagedServiceChangeLocation_12_1_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeLocation_12_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1,
bundleT2.getLocation());
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("conf.setBundleLocation() is being called.");
conf.setBundleLocation("?RegionA");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
// count1_2 = assertCallback(sync1_2, count1_2);
// assertNull("called back with null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, null, list);
}
}
public void testManagedServiceChangeLocation_12_1_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeLocation_12_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
assertEquals("conf.location must be set to \"?RegionA\".",
conf.getBundleLocation(), "?RegionA");
trace("conf.setBundleLocation() is being called.");
conf.setBundleLocation(bundleT2.getLocation());
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, null, list);
}
}
public void testManagedServiceChangeLocation_12_1_3() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeLocation_12_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
assertEquals("conf.location must be set to \"?RegionA\".",
conf.getBundleLocation(), "?RegionA");
trace("conf.setBundleLocation() is being called.");
conf.setBundleLocation("?RegionB");
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, null, list);
}
}
public void testManagedServiceChangeCP_12_2_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeCP_12_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
props.put("StringKey", "stringvalueNew");
trace("The configuration is being updated ");
conf.update(props);
//count1_1 = assertCallback(sync1_1, count1_1);
//assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceChangeCP_12_2_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceChangeCP_12_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.setCPtoBundle("*", "target", bundleT1, false);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
props.put("StringKey", "stringvalueNew");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceStartCM_12_3_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceStartCM_12_3_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
Bundle cmBundle = this.stopCmBundle();
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
int count1_2 = 0;
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("CM is going to start");
startCmBundle(cmBundle);
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceStartCM_12_3_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceStartCM_12_3_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
// Dictionary props = new Hashtable();
// props.put("StringKey", "stringvalue");
// trace("The configuration is being updated ");
// conf.update(props);
Bundle cmBundle = this.stopCmBundle();
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
int count1_2 = 0;
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("CM is going to start");
startCmBundle(cmBundle);
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceStartCM_12_3_3() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
List list = new ArrayList(5);
final String header = "testManagedServiceStartCM_12_3_3";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?RegionA");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
Bundle cmBundle = this.stopCmBundle();
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
int count1_2 = 0;
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("CM is going to start");
startCmBundle(cmBundle);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceModifyPid_12_4_1() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
final String pid2 = Util.createPid("pid2");
List list = new ArrayList(5);
final String header = "testManagedServiceModifyPid_12_4_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
// modify PID
trace("modify PID from " + pid1 + " to " + pid2);
modifyPid(ManagedService.class.getName(), pid1, pid2);
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceModifyPid_12_4_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String pid1 = Util.createPid("pid1");
final String pid2 = Util.createPid("pid2");
List list = new ArrayList(5);
final String header = "testManagedServiceModifyPid_12_4_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSync1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSync1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
count1_1 = assertCallback(sync1_1, count1_1);
assertNull("called back with null props", sync1_1.getProps());
int count1_2 = 0;
count1_2 = assertCallback(sync1_2, count1_2);
assertNull("called back with null props", sync1_2.getProps());
trace("The configuration is being created");
Configuration conf = cm.getConfiguration(pid1, "?");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
trace("The configuration is being updated ");
conf.update(props);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
// modify PID
trace("modify PID from " + pid2 + " to " + pid1);
modifyPid(ManagedService.class.getName(), pid2, pid1);
assertNoCallback(sync1_1, count1_1);
count1_1 = assertCallback(sync1_2, count1_2);
assertNotNull("called back with NON-null props", sync1_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
private void modifyPid(String clazz, String oldPid, String newPid) {
ServiceReference reference1 = this.getContext().getServiceReference(
ModifyPid.class.getName());
ModifyPid modifyPid = (ModifyPid) this.getContext().getService(
reference1);
ServiceReference[] references = null;
try {
references = this.getContext().getServiceReferences(clazz,
"(service.pid=" + oldPid + ")");
} catch (InvalidSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
trace("The pid of MS1-1 is being changed from " + oldPid + " to "
+ newPid);
modifyPid.changeMsPid(
(Long) (references[0].getProperty(Constants.SERVICE_ID)),
newPid);
}
public void testManagedServiceFactoryRegistration13_1_1() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryRegistration13_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
this.setCPtoBundle(null, null, bundleT1, false);
checkMsf_FirstRegThenCreateConf(bundleT1, fpid1, list,
bundleT1.getLocation(), true);
}
private void checkMsf_FirstRegThenCreateConf(Bundle bundleT1,
final String fpid1, List list, final String location,
boolean toBeCalledBack) throws BundleException, IOException {
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
int count1_1 = 0;
int count1_2 = 0;
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, location);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
if (toBeCalledBack) {
count1_1 = assertCallback(sync1_1, count1_1);
props = sync1_1.getProps();
assertNotNull("null props must be called back", props);
assertNotNull("pid", props.get(Constants.SERVICE_PID));
assertFalse("pid",
props.get(Constants.SERVICE_PID).equals(fpid1));
assertEquals("fpid", fpid1,
props.get(ConfigurationAdmin.SERVICE_FACTORYPID));
assertEquals("value", "stringvalue", props.get("stringkey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 3", 3, props.size());
} else {
assertNoCallback(sync1_1, count1_1);
}
assertNoCallback(sync1_2, count1_2);
restartCM();
if (toBeCalledBack) {
count1_1 = assertCallback(sync1_1, count1_1);
props = sync1_1.getProps();
assertNotNull("null props must be called back", props);
assertNotNull("pid", props.get(Constants.SERVICE_PID));
assertFalse("pid",
props.get(Constants.SERVICE_PID).equals(fpid1));
assertEquals("fpid", fpid1,
props.get(ConfigurationAdmin.SERVICE_FACTORYPID));
assertEquals("value", "stringvalue", props.get("stringkey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 3", 3, props.size());
} else {
assertNoCallback(sync1_1, count1_1);
}
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryRegistration13_1_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryRegistration11_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
this.setCPtoBundle(null, null, bundleT1, false);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
bundleT1.getLocation());
int count1_1 = 0;
int count1_2 = 0;
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("Bundle is going to stop.");
bundleT1.stop();
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
props = sync1_1.getProps();
assertNotNull("null props must be called back", props);
assertNotNull("pid", props.get(Constants.SERVICE_PID));
assertFalse("pid", props.get(Constants.SERVICE_PID).equals(fpid1));
assertEquals("fpid", fpid1,
props.get(ConfigurationAdmin.SERVICE_FACTORYPID));
assertEquals("value", "stringvalue", props.get("stringkey"));
assertNull("bundleLocation must be not included",
props.get("service.bundleLocation"));
assertEquals("Size of props must be 3", 3, props.size());
trace("The configuration is being deleted. Wait for signal.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryRegistration13_2_2() throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
/*
* A. Register in advance. Then create Configuration.
*/
final String header = "testManagedServiceFactoryRegistration13_2_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
this.setCPtoBundle("*", "target", bundleT1, false);
checkMsf_FirstRegThenCreateConf(bundleT1, fpid1, list,
bundleT2.getLocation(), false);
}
public void testManagedServiceFactoryRegistration13_2_5() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryRegistration13_2_5";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
this.setCPtoBundle(null, null, bundleT1, false);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
bundleT2.getLocation());
int count1_1 = 0;
int count1_2 = 0;
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1);
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("Bundle is going to stop.");
bundleT1.stop();
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
// count1_1 = assertCallback(sync1_1, count1_1);
// assertNotNull("called back with NON-null props",
// sync1_1.getProps());
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
// props = sync1_1.getProps();
// assertNotNull("null props must be called back", props);
// assertNotNull("pid", props.get(Constants.SERVICE_PID));
// assertFalse("pid",
// props.get(Constants.SERVICE_PID).equals(fpid1));
// assertEquals("fpid", fpid1,
// props.get(ConfigurationAdmin.SERVICE_FACTORYPID));
// assertEquals("value", "stringvalue", props.get("stringkey"));
// assertNull("bundleLocation must be not included",
// props.get("service.bundleLocation"));
// assertEquals("Size of props must be 3", 3, props.size());
trace("The configuration is being deleted. Wait for signal.");
conf.delete();
this.assertDeletedNoCallback(sync1_1, 0);
// count1_1 = this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_14_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
// final Bundle bundleT4 = getContext().installBundle(
// getWebServer() + "bundleT4.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_14_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?*", "target", bundleT2, false);
this.setCPtoBundle("?RegionA", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
this.assertDeletedCallback(sync2_1, 0);
this.assertDeletedCallback(sync3_1, 0);
this.assertDeletedCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_14_1_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
// final Bundle bundleT4 = getContext().installBundle(
// getWebServer() + "bundleT4.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_14_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle("?RegionB", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
this.assertDeletedNoCallback(sync2_1, 0);
this.assertDeletedNoCallback(sync3_1, 0);
this.assertDeletedNoCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_14_2_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_14_2_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?*", "target", bundleT2, false);
this.setCPtoBundle("?RegionA", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
this.startTargetBundle(bundleT1);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
this.startTargetBundle(bundleT3);
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
this.assertDeletedCallback(sync2_1, 0);
this.assertDeletedCallback(sync3_1, 0);
this.assertDeletedCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_14_2_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_14_2_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle("?RegionB", "target", bundleT3, false);
// this.setCPtoBundle("?*", "target", bundleT2, false);
// this.setCPtoBundle("?RegionA", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
this.startTargetBundle(bundleT1);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
this.assertDeletedNoCallback(sync2_1, 0);
this.assertDeletedNoCallback(sync3_1, 0);
this.assertDeletedNoCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_15_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
//final Bundle bundleT3 = getContext().installBundle(
// getWebServer() + "bundleT3.jar");
// final Bundle bundleT4 = getContext().installBundle(
// getWebServer() + "bundleT4.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_15_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
//SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
//list.add(getContext().registerService(Synchronizer.class.getName(),
// sync3_1, propsForSyncF3_1));
//SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
//list.add(getContext().registerService(Synchronizer.class.getName(),
// sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle("*", "target", bundleT2, false);
//this.setCPtoBundle("*", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
//int count3_1 = 0;
//int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
//this.startTargetBundle(bundleT3);
//assertNoCallback(sync3_1, count3_1);
//assertNoCallback(sync3_2, count3_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, null);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
//assertNoCallback(sync3_1, count3_1);
//assertNoCallback(sync3_2, count3_2);
// assertEquals(
// "The location of the conf must be dynamically bound to bundleT2",
// bundleT2.getLocation(), conf.getBundleLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
sleep(1000);
if(conf.getBundleLocation().equals(bundleT1.getLocation())){
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertEquals(
"The location of the conf must be dynamically bound to bundleT1",
bundleT1.getLocation(), conf.getBundleLocation());
trace("Bound bundleT1 is going to be stopped.");
bundleT1.stop();
bundleT1.uninstall();
sleep(1000);
assertEquals(
"The location of the conf must be dynamically bound to bundleT2",
bundleT2.getLocation(), conf.getBundleLocation());
count2_1 = assertCallback(sync2_1, count2_1);
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync2_1, 0);
bundleT2.stop();
bundleT2.uninstall();
}else if(conf.getBundleLocation().equals(bundleT2.getLocation())){
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
assertEquals(
"The location of the conf must be dynamically bound to bundleT2",
bundleT2.getLocation(), conf.getBundleLocation());
trace("Bound bundleT2 is going to be stopped.");
bundleT2.stop();
bundleT2.uninstall();
sleep(1000);
assertEquals(
"The location of the conf must be dynamically bound to bundleT1",
bundleT1.getLocation(), conf.getBundleLocation());
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
trace("conf is going to be deleted.");
conf.delete();
this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
bundleT1.stop();
bundleT1.uninstall();
}else{
fail();
}
//trace("Wait for signal.");
//assertNoCallback(sync1_1, count1_1);
//assertNoCallback(sync1_2, count1_2);
//count2_1 = assertCallback(sync2_1, count2_1);
//assertNotNull("called back with Non-null props", sync2_1.getProps());
//assertNoCallback(sync3_1, count3_1);
//assertNoCallback(sync3_2, count3_2);
//trace("Bound bundleT2 is going to be stopped.");
//bundleT2.stop();
//assertEquals(
// "The location of the conf must be dynamically bound to bundleT3",
// bundleT3.getLocation(), conf.getBundleLocation());
// TODO confirm the behavior when the MSF gets unvisible. Will
// deleted(pid) be called back ?
//assertNoCallback(sync1_1, count1_1);
//assertNoCallback(sync1_2, count1_2);
//int countDeleted2_1 = this.assertDeletedCallback(sync2_1, 0);
//count3_1 = assertCallback(sync3_1, count3_1);
//assertNotNull("called back with Non-null props", sync3_1.getProps());
//count3_1 = assertCallback(sync3_2, count3_2);
//assertNotNull("called back with Non-null props", sync3_2.getProps());
//trace("conf is going to be deleted.");
//conf.delete();
//this.assertDeletedNoCallback(sync1_1, 0);
//this.assertDeletedNoCallback(sync1_2, 0);
//this.assertDeletedNoCallback(sync2_1, countDeleted2_1);
//this.assertDeletedCallback(sync3_1, 0);
//this.assertDeletedCallback(sync3_2, 0);
} finally {
cleanUpForCallbackTest(null, null, null, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_15_1_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_15_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
int count1_1 = 0;
int count1_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, null);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertEquals(
"The location of the conf must be dynamically bound to bundleT1",
bundleT1.getLocation(), conf.getBundleLocation());
trace("Bound bundleT1 is going to be stopped.");
bundleT1.stop();
bundleT1.uninstall();
sleep(1000);
assertNull(
"The location of the conf must be dynamically unbound to null.",
conf.getBundleLocation());
} finally {
cleanUpForCallbackTest(null, null, null, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleTargets_15_2_1()
throws Exception {
// TODO impl
}
public void testManagedServiceFactoryRegistrationMultipleTargets_15_3_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
// final Bundle bundleT4 = getContext().installBundle(
// getWebServer() + "bundleT4.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleTargets_15_3_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("*", "target", bundleT1, false);
this.setCPtoBundle(bundleT2.getLocation(), "target", bundleT2,
false);
this.setCPtoBundle("?", "target", bundleT3, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, "?");
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
this.printoutPermissions();
props.put("StringKey", "stringvalue");
conf.update(props);
this.startTargetBundle(bundleT1);
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleCF_16_1_1()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleCF_16_1_1";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("?RegionA", "target", bundleT1, false);
this.setCPtoBundle("?RegionB", "target", bundleT2, false);
this.setCPtoBundle(null, null, bundleT3, false);
// this.setCPtoBundle(null, null, bundleT2, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configurations are being created");
Configuration conf1 = cm.createFactoryConfiguration(fpid1,
"?RegionA");
Configuration conf2 = cm.createFactoryConfiguration(fpid1, "?");
Configuration conf3 = cm.createFactoryConfiguration(fpid1,
bundleT3.getLocation());
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf1 is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf1.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf2 is being updated ");
conf2.update(props);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
// count2_1 = assertCallback(sync2_1, count2_1);
// assertNotNull("called back with Non-null props",
// sync2_1.getProps());
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf3 is being updated ");
conf3.update(props);
trace("Wait for signal.");
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryRegistrationMultipleCF_16_1_2()
throws Exception {
final Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final Bundle bundleT2 = getContext().installBundle(
getWebServer() + "bundleT2.jar");
final Bundle bundleT3 = getContext().installBundle(
getWebServer() + "bundleT3.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(5);
final String header = "testManagedServiceFactoryRegistrationMultipleCF_16_1_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
SynchronizerImpl sync1_1 = new SynchronizerImpl("1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
SynchronizerImpl sync2_1 = new SynchronizerImpl("2-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync2_1, propsForSyncF2_1));
SynchronizerImpl sync3_1 = new SynchronizerImpl("3-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_1, propsForSyncF3_1));
SynchronizerImpl sync3_2 = new SynchronizerImpl("3-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync3_2, propsForSyncF3_2));
this.resetPermissions();
this.setCPtoBundle("?*", "target", bundleT1, false);
this.setCPtoBundle("?", "target", bundleT2, false);
this.setCPtoBundle(null, null, bundleT3, false);
// this.setCPtoBundle(null, null, bundleT2, false);
int count1_1 = 0;
int count1_2 = 0;
int count2_1 = 0;
int count3_1 = 0;
int count3_2 = 0;
this.startTargetBundle(bundleT1);
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
this.startTargetBundle(bundleT2);
assertNoCallback(sync2_1, count2_1);
this.startTargetBundle(bundleT3);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The configurations are being created");
Configuration conf1 = cm.createFactoryConfiguration(fpid1,
"?RegionA");
Configuration conf2 = cm.createFactoryConfiguration(fpid1, "?");
Configuration conf3 = cm.createFactoryConfiguration(fpid1,
bundleT3.getLocation());
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf1 is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf1.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
assertNoCallback(sync2_1, count2_1);
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf2 is being updated ");
conf2.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with Non-null props", sync1_1.getProps());
// assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
count2_1 = assertCallback(sync2_1, count2_1);
assertNotNull("called back with Non-null props", sync2_1.getProps());
assertNoCallback(sync3_1, count3_1);
assertNoCallback(sync3_2, count3_2);
trace("The conf3 is being updated ");
conf3.update(props);
trace("Wait for signal.");
count3_1 = assertCallback(sync3_1, count3_1);
assertNotNull("called back with Non-null props", sync3_1.getProps());
count3_2 = assertCallback(sync3_2, count3_2);
assertNotNull("called back with Non-null props", sync3_2.getProps());
} finally {
cleanUpForCallbackTest(bundleT1, bundleT2, bundleT3, list);
}
}
public void testManagedServiceFactoryCmRestart18_3_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryCmRestart18_3_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
bundleT1.getLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("CM Bundle is going to start.");
Bundle cmBundle = stopCmBundle();
this.setCPtoBundle("*", "target", bundleT1, false);
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
int count1_1 = 0;
int count1_2 = 0;
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
assertNoCallback(sync1_2, count1_2);
trace("CM Bundle is going to start.");
this.startTargetBundle(cmBundle);
assignCm();
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryModifyPid18_4_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
final String fpid2 = Util.createPid("factoryPid2");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryModifyPid18_4_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
this.setCPtoBundle("*", "target", bundleT1, false);
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
int count1_1 = 0;
int count1_2 = 0;
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1, "?");
// Configuration conf =
// cm.createFactoryConfiguration(fpid1,bundleT1.getLocation());
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
// modify PID
modifyPid(ManagedServiceFactory.class.getName(), fpid2, fpid1);
// ServiceReference[] references = this.getContext()
// .getServiceReferences(
// ManagedServiceFactory.class.getName(), null);
trace("Wait for signal.");
assertNoCallback(sync1_1, count1_1);
count1_2 = assertCallback(sync1_2, count1_2);
assertNotNull("called back with NON-null props", sync1_2.getProps());
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
public void testManagedServiceFactoryDeletion18_5_2() throws Exception {
Bundle bundleT1 = getContext().installBundle(
getWebServer() + "bundleT1.jar");
final String fpid1 = Util.createPid("factoryPid1");
List list = new ArrayList(3);
final String header = "testManagedServiceFactoryDeletion18_5_2";
String testId = null;
int micro = 0;
testId = traceTestId(header, ++micro);
try {
trace("The configuration is being created");
Configuration conf = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("The configuration is being updated ");
Dictionary props = new Hashtable();
props.put("StringKey", "stringvalue");
conf.update(props);
this.setCPtoBundle("*", "target", bundleT1, false);
SynchronizerImpl sync1_1 = new SynchronizerImpl("F1-1");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_1, propsForSyncF1_1));
SynchronizerImpl sync1_2 = new SynchronizerImpl("F1-2");
list.add(getContext().registerService(Synchronizer.class.getName(),
sync1_2, propsForSyncF1_2));
int count1_1 = 0;
int count1_2 = 0;
trace("Bundle is going to start.");
this.startTargetBundle(bundleT1);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
trace("The configuration is being deleted. Wait for signal.");
conf.delete();
int countDeteted1_1 = this.assertDeletedCallback(sync1_1, 0);
this.assertDeletedNoCallback(sync1_2, 0);
trace("The configuration is being created");
Configuration conf2 = cm.createFactoryConfiguration(fpid1,
"?RegionA");
trace("The configuration is being updated ");
conf2.update(props);
trace("Wait for signal.");
count1_1 = assertCallback(sync1_1, count1_1);
assertNotNull("called back with NON-null props", sync1_1.getProps());
assertNoCallback(sync1_2, count1_2);
trace("Change permission of bundleT1 ");
this.setCPtoBundle(null, null, bundleT1, false);
trace("The configuration is being deleted. Wait for signal.");
conf2.delete();
this.assertDeletedNoCallback(sync1_1, countDeteted1_1);
this.assertDeletedNoCallback(sync1_2, 0);
} finally {
this.cleanUpForCallbackTest(bundleT1, null, null, list);
}
}
}
| Bug 2546: Fix CT to properly check callbacks on ManagedServices when
the location changes.
This removes old comments and code which date back to CM 1.4 which did
not reassign configurations when the location was set to null.
| org.osgi.test.cases.cm/src/org/osgi/test/cases/cm/junit/CMControl.java | Bug 2546: Fix CT to properly check callbacks on ManagedServices when the location changes. |
|
Java | apache-2.0 | aed73197a2c27b37c63fb3b8b448d38409386ce0 | 0 | bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud | package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.StdAbility;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.ExpertiseLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2003-2020 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Spell_EnchantWand extends Spell
{
@Override
public String ID()
{
return "Spell_EnchantWand";
}
private final static String localizedName = CMLib.lang().L("Enchant Wand");
@Override
public String name()
{
return localizedName;
}
@Override
protected int canTargetCode()
{
return CAN_ITEMS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_SPELL|Ability.DOMAIN_ENCHANTMENT;
}
@Override
public long flags()
{
return Ability.FLAG_NOORDERING;
}
@Override
protected int overrideMana()
{
return Ability.COST_ALL;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if(commands.size()<2)
{
mob.tell(L("Enchant which spell onto what?"));
return false;
}
final Physical target=mob.location().fetchFromMOBRoomFavorsItems(mob,null,commands.get(commands.size()-1),Wearable.FILTER_UNWORNONLY);
if((target==null)||(!CMLib.flags().canBeSeenBy(target,mob)))
{
mob.tell(L("You don't see '@x1' here.",(commands.get(commands.size()-1))));
return false;
}
if(!(target instanceof Wand))
{
mob.tell(mob,target,null,L("You can't enchant <T-NAME>."));
return false;
}
if((((Wand)target).getEnchantType()!=-1)
&&(((Wand)target).getEnchantType()!=Ability.ACODE_SPELL))
{
mob.tell(mob,target,null,L("You can't enchant <T-NAME> with this spell."));
return false;
}
commands.remove(commands.size()-1);
final Wand wand=(Wand)target;
final String spellName=CMParms.combine(commands,0).trim();
Ability wandThis=null;
for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL)
&&((!A.isSavable())||(CMLib.ableMapper().qualifiesByLevel(mob,A)))
&&(A.name().equalsIgnoreCase(spellName))
&&(!A.ID().equals(this.ID())))
wandThis=A;
}
if(wandThis==null)
{
for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL)
&&((!A.isSavable())||(CMLib.ableMapper().qualifiesByLevel(mob,A)))
&&(CMLib.english().containsString(A.name(),spellName))
&&(!A.ID().equals(this.ID())))
wandThis=A;
}
}
if(wandThis==null)
{
mob.tell(L("You don't know how to enchant anything with '@x1'.",spellName));
return false;
}
if((CMLib.ableMapper().lowestQualifyingLevel(wandThis.ID())>24)
||(((StdAbility)wandThis).usageCost(null,true)[0]>45)
||(CMath.bset(wandThis.flags(), Ability.FLAG_CLANMAGIC)))
{
mob.tell(L("That spell is too powerful to enchant into wands."));
return false;
}
if(wand.getSpell()!=null)
{
mob.tell(L("A spell has already been enchanted into '@x1'.",wand.name()));
return false;
}
int experienceToLose=10*CMLib.ableMapper().lowestQualifyingLevel(wandThis.ID());
if((mob.getExperience()-experienceToLose)<0)
{
mob.tell(L("You don't have enough experience to cast this spell."));
return false;
}
// lose all the mana!
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
experienceToLose=getXPCOSTAdjustment(mob,experienceToLose);
experienceToLose=-CMLib.leveler().postExperience(mob,null,null,-experienceToLose,false);
mob.tell(L("You lose @x1 experience points for the effort.",""+experienceToLose));
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
setMiscText(wandThis.ID());
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),L("^S<S-NAME> move(s) <S-HIS-HER> fingers around <T-NAMESELF>, incanting softly.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
wand.setSpell((Ability)wandThis.copyOf());
if((wand.usesRemaining()==Integer.MAX_VALUE)||(wand.usesRemaining()<0))
wand.setUsesRemaining(0);
final int lowestSpellLevel = CMLib.ableMapper().lowestQualifyingLevel(wandThis.ID());
if(lowestSpellLevel > wand.basePhyStats().level())
wand.basePhyStats().setLevel(lowestSpellLevel);
wand.setUsesRemaining(wand.usesRemaining()+5);
wand.text();
wand.recoverPhyStats();
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> move(s) <S-HIS-HER> fingers around <T-NAMESELF>, incanting softly, and looking very frustrated."));
// return whether it worked
return success;
}
}
| com/planet_ink/coffee_mud/Abilities/Spells/Spell_EnchantWand.java | package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.StdAbility;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.ExpertiseLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2003-2020 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Spell_EnchantWand extends Spell
{
@Override
public String ID()
{
return "Spell_EnchantWand";
}
private final static String localizedName = CMLib.lang().L("Enchant Wand");
@Override
public String name()
{
return localizedName;
}
@Override
protected int canTargetCode()
{
return CAN_ITEMS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_SPELL|Ability.DOMAIN_ENCHANTMENT;
}
@Override
public long flags()
{
return Ability.FLAG_NOORDERING;
}
@Override
protected int overrideMana()
{
return Ability.COST_ALL;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if(commands.size()<2)
{
mob.tell(L("Enchant which spell onto what?"));
return false;
}
final Physical target=mob.location().fetchFromMOBRoomFavorsItems(mob,null,commands.get(commands.size()-1),Wearable.FILTER_UNWORNONLY);
if((target==null)||(!CMLib.flags().canBeSeenBy(target,mob)))
{
mob.tell(L("You don't see '@x1' here.",(commands.get(commands.size()-1))));
return false;
}
if(!(target instanceof Wand))
{
mob.tell(mob,target,null,L("You can't enchant <T-NAME>."));
return false;
}
if((((Wand)target).getEnchantType()!=-1)
&&(((Wand)target).getEnchantType()!=Ability.ACODE_SPELL))
{
mob.tell(mob,target,null,L("You can't enchant <T-NAME> with this spell."));
return false;
}
commands.remove(commands.size()-1);
final Wand wand=(Wand)target;
final String spellName=CMParms.combine(commands,0).trim();
Ability wandThis=null;
for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL)
&&((!A.isSavable())||(CMLib.ableMapper().qualifiesByLevel(mob,A)))
&&(A.name().equalsIgnoreCase(spellName))
&&(!A.ID().equals(this.ID())))
wandThis=A;
}
if(wandThis==null)
{
for(final Enumeration<Ability> a=mob.allAbilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL)
&&((!A.isSavable())||(CMLib.ableMapper().qualifiesByLevel(mob,A)))
&&(CMLib.english().containsString(A.name(),spellName))
&&(!A.ID().equals(this.ID())))
wandThis=A;
}
}
if(wandThis==null)
{
mob.tell(L("You don't know how to enchant anything with '@x1'.",spellName));
return false;
}
if((CMLib.ableMapper().lowestQualifyingLevel(wandThis.ID())>24)
||(((StdAbility)wandThis).usageCost(null,true)[0]>45)
||(CMath.bset(wandThis.flags(), Ability.FLAG_CLANMAGIC)))
{
mob.tell(L("That spell is too powerful to enchant into wands."));
return false;
}
if(wand.getSpell()!=null)
{
mob.tell(L("A spell has already been enchanted into '@x1'.",wand.name()));
return false;
}
int experienceToLose=10*CMLib.ableMapper().lowestQualifyingLevel(wandThis.ID());
if((mob.getExperience()-experienceToLose)<0)
{
mob.tell(L("You don't have enough experience to cast this spell."));
return false;
}
// lose all the mana!
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
experienceToLose=getXPCOSTAdjustment(mob,experienceToLose);
experienceToLose=-CMLib.leveler().postExperience(mob,null,null,-experienceToLose,false);
mob.tell(L("You lose @x1 experience points for the effort.",""+experienceToLose));
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
setMiscText(wandThis.ID());
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),L("^S<S-NAME> move(s) <S-HIS-HER> fingers around <T-NAMESELF>, incanting softly.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
wand.setSpell((Ability)wandThis.copyOf());
if((wand.usesRemaining()==Integer.MAX_VALUE)||(wand.usesRemaining()<0))
wand.setUsesRemaining(0);
final int newLevel=wandThis.adjustedLevel(mob, asLevel);
if(newLevel > wand.basePhyStats().level())
wand.basePhyStats().setLevel(newLevel);
wand.setUsesRemaining(wand.usesRemaining()+5);
wand.text();
wand.recoverPhyStats();
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> move(s) <S-HIS-HER> fingers around <T-NAMESELF>, incanting softly, and looking very frustrated."));
// return whether it worked
return success;
}
}
| Enchant Wand only raises wand level when LOWEST qualifying level of spell is higher. This allows builders to better control the power of the magic.
git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@19109 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/Abilities/Spells/Spell_EnchantWand.java | Enchant Wand only raises wand level when LOWEST qualifying level of spell is higher. This allows builders to better control the power of the magic. |
|
Java | apache-2.0 | 06a260f107ba5ab489e7d28256ee6bc9530d3416 | 0 | vincentpoon/hbase,francisliu/hbase,Eshcar/hbase,francisliu/hbase,gustavoanatoly/hbase,Apache9/hbase,Apache9/hbase,HubSpot/hbase,HubSpot/hbase,bijugs/hbase,francisliu/hbase,apurtell/hbase,Eshcar/hbase,Apache9/hbase,bijugs/hbase,JingchengDu/hbase,JingchengDu/hbase,HubSpot/hbase,HubSpot/hbase,mahak/hbase,ndimiduk/hbase,vincentpoon/hbase,Eshcar/hbase,ndimiduk/hbase,HubSpot/hbase,francisliu/hbase,vincentpoon/hbase,gustavoanatoly/hbase,ultratendency/hbase,Apache9/hbase,gustavoanatoly/hbase,apurtell/hbase,HubSpot/hbase,mahak/hbase,francisliu/hbase,mahak/hbase,ndimiduk/hbase,Eshcar/hbase,ultratendency/hbase,gustavoanatoly/hbase,mahak/hbase,bijugs/hbase,HubSpot/hbase,gustavoanatoly/hbase,JingchengDu/hbase,ChinmaySKulkarni/hbase,gustavoanatoly/hbase,francisliu/hbase,ultratendency/hbase,francisliu/hbase,vincentpoon/hbase,ndimiduk/hbase,JingchengDu/hbase,JingchengDu/hbase,HubSpot/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,Eshcar/hbase,bijugs/hbase,HubSpot/hbase,bijugs/hbase,mahak/hbase,apurtell/hbase,bijugs/hbase,HubSpot/hbase,bijugs/hbase,gustavoanatoly/hbase,Apache9/hbase,Apache9/hbase,ndimiduk/hbase,francisliu/hbase,Eshcar/hbase,vincentpoon/hbase,mahak/hbase,mahak/hbase,francisliu/hbase,ultratendency/hbase,mahak/hbase,francisliu/hbase,vincentpoon/hbase,JingchengDu/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,vincentpoon/hbase,bijugs/hbase,bijugs/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,gustavoanatoly/hbase,Apache9/hbase,Apache9/hbase,gustavoanatoly/hbase,apurtell/hbase,gustavoanatoly/hbase,apurtell/hbase,JingchengDu/hbase,ndimiduk/hbase,ultratendency/hbase,ultratendency/hbase,Eshcar/hbase,Apache9/hbase,Eshcar/hbase,vincentpoon/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,apurtell/hbase,bijugs/hbase,ultratendency/hbase,JingchengDu/hbase,JingchengDu/hbase,ndimiduk/hbase,Eshcar/hbase,mahak/hbase,vincentpoon/hbase,ultratendency/hbase,ultratendency/hbase,Eshcar/hbase,ndimiduk/hbase,apurtell/hbase,Apache9/hbase,JingchengDu/hbase,ChinmaySKulkarni/hbase,mahak/hbase,apurtell/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase,ultratendency/hbase,vincentpoon/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.ClusterManager.ServiceType;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ClusterConnection;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ServerInfo;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MasterService;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Threads;
/**
* Manages the interactions with an already deployed distributed cluster (as opposed to
* a pseudo-distributed, or mini/local cluster). This is used by integration and system tests.
*/
@InterfaceAudience.Private
public class DistributedHBaseCluster extends HBaseCluster {
private Admin admin;
private final Connection connection;
private ClusterManager clusterManager;
public DistributedHBaseCluster(Configuration conf, ClusterManager clusterManager)
throws IOException {
super(conf);
this.clusterManager = clusterManager;
this.connection = ConnectionFactory.createConnection(conf);
this.admin = this.connection.getAdmin();
this.initialClusterStatus = getClusterStatus();
}
public void setClusterManager(ClusterManager clusterManager) {
this.clusterManager = clusterManager;
}
public ClusterManager getClusterManager() {
return clusterManager;
}
/**
* Returns a ClusterStatus for this HBase cluster
* @throws IOException
*/
@Override
public ClusterStatus getClusterStatus() throws IOException {
return admin.getClusterStatus();
}
@Override
public ClusterStatus getInitialClusterStatus() throws IOException {
return initialClusterStatus;
}
@Override
public void close() throws IOException {
if (this.admin != null) {
admin.close();
}
if (this.connection != null && !this.connection.isClosed()) {
this.connection.close();
}
}
@Override
public AdminProtos.AdminService.BlockingInterface getAdminProtocol(ServerName serverName)
throws IOException {
return ((ClusterConnection)this.connection).getAdmin(serverName);
}
@Override
public ClientProtos.ClientService.BlockingInterface getClientProtocol(ServerName serverName)
throws IOException {
return ((ClusterConnection)this.connection).getClient(serverName);
}
@Override
public void startRegionServer(String hostname, int port) throws IOException {
LOG.info("Starting RS on: " + hostname);
clusterManager.start(ServiceType.HBASE_REGIONSERVER, hostname, port);
}
@Override
public void killRegionServer(ServerName serverName) throws IOException {
LOG.info("Aborting RS: " + serverName.getServerName());
clusterManager.kill(ServiceType.HBASE_REGIONSERVER,
serverName.getHostname(), serverName.getPort());
}
@Override
public void stopRegionServer(ServerName serverName) throws IOException {
LOG.info("Stopping RS: " + serverName.getServerName());
clusterManager.stop(ServiceType.HBASE_REGIONSERVER,
serverName.getHostname(), serverName.getPort());
}
@Override
public void waitForRegionServerToStop(ServerName serverName, long timeout) throws IOException {
waitForServiceToStop(ServiceType.HBASE_REGIONSERVER, serverName, timeout);
}
@Override
public void startZkNode(String hostname, int port) throws IOException {
LOG.info("Starting ZooKeeper node on: " + hostname);
clusterManager.start(ServiceType.ZOOKEEPER_SERVER, hostname, port);
}
@Override
public void killZkNode(ServerName serverName) throws IOException {
LOG.info("Aborting ZooKeeper node on: " + serverName.getServerName());
clusterManager.kill(ServiceType.ZOOKEEPER_SERVER,
serverName.getHostname(), serverName.getPort());
}
@Override
public void stopZkNode(ServerName serverName) throws IOException {
LOG.info("Stopping ZooKeeper node: " + serverName.getServerName());
clusterManager.stop(ServiceType.ZOOKEEPER_SERVER,
serverName.getHostname(), serverName.getPort());
}
@Override
public void waitForZkNodeToStart(ServerName serverName, long timeout) throws IOException {
waitForServiceToStart(ServiceType.ZOOKEEPER_SERVER, serverName, timeout);
}
@Override
public void waitForZkNodeToStop(ServerName serverName, long timeout) throws IOException {
waitForServiceToStop(ServiceType.ZOOKEEPER_SERVER, serverName, timeout);
}
@Override
public void startDataNode(ServerName serverName) throws IOException {
LOG.info("Starting data node on: " + serverName.getServerName());
clusterManager.start(ServiceType.HADOOP_DATANODE,
serverName.getHostname(), serverName.getPort());
}
@Override
public void killDataNode(ServerName serverName) throws IOException {
LOG.info("Aborting data node on: " + serverName.getServerName());
clusterManager.kill(ServiceType.HADOOP_DATANODE,
serverName.getHostname(), serverName.getPort());
}
@Override
public void stopDataNode(ServerName serverName) throws IOException {
LOG.info("Stopping data node on: " + serverName.getServerName());
clusterManager.stop(ServiceType.HADOOP_DATANODE,
serverName.getHostname(), serverName.getPort());
}
@Override
public void waitForDataNodeToStart(ServerName serverName, long timeout) throws IOException {
waitForServiceToStart(ServiceType.HADOOP_DATANODE, serverName, timeout);
}
@Override
public void waitForDataNodeToStop(ServerName serverName, long timeout) throws IOException {
waitForServiceToStop(ServiceType.HADOOP_DATANODE, serverName, timeout);
}
private void waitForServiceToStop(ServiceType service, ServerName serverName, long timeout)
throws IOException {
LOG.info("Waiting for service: " + service + " to stop: " + serverName.getServerName());
long start = System.currentTimeMillis();
while ((System.currentTimeMillis() - start) < timeout) {
if (!clusterManager.isRunning(service, serverName.getHostname(), serverName.getPort())) {
return;
}
Threads.sleep(100);
}
throw new IOException("did timeout waiting for service to stop:" + serverName);
}
private void waitForServiceToStart(ServiceType service, ServerName serverName, long timeout)
throws IOException {
LOG.info("Waiting for service: " + service + " to start: " + serverName.getServerName());
long start = System.currentTimeMillis();
while ((System.currentTimeMillis() - start) < timeout) {
if (clusterManager.isRunning(service, serverName.getHostname(), serverName.getPort())) {
return;
}
Threads.sleep(100);
}
throw new IOException("did timeout waiting for service to start:" + serverName);
}
@Override
public MasterService.BlockingInterface getMasterAdminService()
throws IOException {
return ((ClusterConnection)this.connection).getMaster();
}
@Override
public void startMaster(String hostname, int port) throws IOException {
LOG.info("Starting Master on: " + hostname + ":" + port);
clusterManager.start(ServiceType.HBASE_MASTER, hostname, port);
}
@Override
public void killMaster(ServerName serverName) throws IOException {
LOG.info("Aborting Master: " + serverName.getServerName());
clusterManager.kill(ServiceType.HBASE_MASTER, serverName.getHostname(), serverName.getPort());
}
@Override
public void stopMaster(ServerName serverName) throws IOException {
LOG.info("Stopping Master: " + serverName.getServerName());
clusterManager.stop(ServiceType.HBASE_MASTER, serverName.getHostname(), serverName.getPort());
}
@Override
public void waitForMasterToStop(ServerName serverName, long timeout) throws IOException {
waitForServiceToStop(ServiceType.HBASE_MASTER, serverName, timeout);
}
@Override
public boolean waitForActiveAndReadyMaster(long timeout) throws IOException {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < timeout) {
try {
getMasterAdminService();
return true;
} catch (MasterNotRunningException m) {
LOG.warn("Master not started yet " + m);
} catch (ZooKeeperConnectionException e) {
LOG.warn("Failed to connect to ZK " + e);
}
Threads.sleep(1000);
}
return false;
}
@Override
public ServerName getServerHoldingRegion(TableName tn, byte[] regionName) throws IOException {
HRegionLocation regionLoc = null;
try (RegionLocator locator = connection.getRegionLocator(tn)) {
regionLoc = locator.getRegionLocation(regionName, true);
}
if (regionLoc == null) {
LOG.warn("Cannot find region server holding region " + Bytes.toString(regionName) +
", start key [" + Bytes.toString(HRegionInfo.getStartKey(regionName)) + "]");
return null;
}
AdminProtos.AdminService.BlockingInterface client =
((ClusterConnection)this.connection).getAdmin(regionLoc.getServerName());
ServerInfo info = ProtobufUtil.getServerInfo(null, client);
return ProtobufUtil.toServerName(info.getServerName());
}
@Override
public void waitUntilShutDown() {
// Simply wait for a few seconds for now (after issuing serverManager.kill
throw new RuntimeException("Not implemented yet");
}
@Override
public void shutdown() throws IOException {
// not sure we want this
throw new RuntimeException("Not implemented yet");
}
@Override
public boolean isDistributedCluster() {
return true;
}
@Override
public boolean restoreClusterStatus(ClusterStatus initial) throws IOException {
ClusterStatus current = getClusterStatus();
LOG.info("Restoring cluster - started");
// do a best effort restore
boolean success = true;
success = restoreMasters(initial, current) & success;
success = restoreRegionServers(initial, current) & success;
success = restoreAdmin() & success;
LOG.info("Restoring cluster - done");
return success;
}
protected boolean restoreMasters(ClusterStatus initial, ClusterStatus current) {
List<IOException> deferred = new ArrayList<IOException>();
//check whether current master has changed
final ServerName initMaster = initial.getMaster();
if (!ServerName.isSameHostnameAndPort(initMaster, current.getMaster())) {
LOG.info("Restoring cluster - Initial active master : "
+ initMaster.getHostAndPort()
+ " has changed to : "
+ current.getMaster().getHostAndPort());
// If initial master is stopped, start it, before restoring the state.
// It will come up as a backup master, if there is already an active master.
try {
if (!clusterManager.isRunning(ServiceType.HBASE_MASTER,
initMaster.getHostname(), initMaster.getPort())) {
LOG.info("Restoring cluster - starting initial active master at:"
+ initMaster.getHostAndPort());
startMaster(initMaster.getHostname(), initMaster.getPort());
}
// master has changed, we would like to undo this.
// 1. Kill the current backups
// 2. Stop current master
// 3. Start backup masters
for (ServerName currentBackup : current.getBackupMasters()) {
if (!ServerName.isSameHostnameAndPort(currentBackup, initMaster)) {
LOG.info("Restoring cluster - stopping backup master: " + currentBackup);
stopMaster(currentBackup);
}
}
LOG.info("Restoring cluster - stopping active master: " + current.getMaster());
stopMaster(current.getMaster());
waitForActiveAndReadyMaster(); // wait so that active master takes over
} catch (IOException ex) {
// if we fail to start the initial active master, we do not want to continue stopping
// backup masters. Just keep what we have now
deferred.add(ex);
}
//start backup masters
for (ServerName backup : initial.getBackupMasters()) {
try {
//these are not started in backup mode, but we should already have an active master
if (!clusterManager.isRunning(ServiceType.HBASE_MASTER,
backup.getHostname(),
backup.getPort())) {
LOG.info("Restoring cluster - starting initial backup master: "
+ backup.getHostAndPort());
startMaster(backup.getHostname(), backup.getPort());
}
} catch (IOException ex) {
deferred.add(ex);
}
}
} else {
//current master has not changed, match up backup masters
Set<ServerName> toStart = new TreeSet<ServerName>(new ServerNameIgnoreStartCodeComparator());
Set<ServerName> toKill = new TreeSet<ServerName>(new ServerNameIgnoreStartCodeComparator());
toStart.addAll(initial.getBackupMasters());
toKill.addAll(current.getBackupMasters());
for (ServerName server : current.getBackupMasters()) {
toStart.remove(server);
}
for (ServerName server: initial.getBackupMasters()) {
toKill.remove(server);
}
for (ServerName sn:toStart) {
try {
if(!clusterManager.isRunning(ServiceType.HBASE_MASTER, sn.getHostname(), sn.getPort())) {
LOG.info("Restoring cluster - starting initial backup master: " + sn.getHostAndPort());
startMaster(sn.getHostname(), sn.getPort());
}
} catch (IOException ex) {
deferred.add(ex);
}
}
for (ServerName sn:toKill) {
try {
if(clusterManager.isRunning(ServiceType.HBASE_MASTER, sn.getHostname(), sn.getPort())) {
LOG.info("Restoring cluster - stopping backup master: " + sn.getHostAndPort());
stopMaster(sn);
}
} catch (IOException ex) {
deferred.add(ex);
}
}
}
if (!deferred.isEmpty()) {
LOG.warn("Restoring cluster - restoring region servers reported "
+ deferred.size() + " errors:");
for (int i=0; i<deferred.size() && i < 3; i++) {
LOG.warn(deferred.get(i));
}
}
return deferred.isEmpty();
}
private static class ServerNameIgnoreStartCodeComparator implements Comparator<ServerName> {
@Override
public int compare(ServerName o1, ServerName o2) {
int compare = o1.getHostname().compareToIgnoreCase(o2.getHostname());
if (compare != 0) return compare;
compare = o1.getPort() - o2.getPort();
if (compare != 0) return compare;
return 0;
}
}
protected boolean restoreRegionServers(ClusterStatus initial, ClusterStatus current) {
Set<ServerName> toStart = new TreeSet<ServerName>(new ServerNameIgnoreStartCodeComparator());
Set<ServerName> toKill = new TreeSet<ServerName>(new ServerNameIgnoreStartCodeComparator());
toStart.addAll(initial.getServers());
toKill.addAll(current.getServers());
ServerName master = initial.getMaster();
for (ServerName server : current.getServers()) {
toStart.remove(server);
}
for (ServerName server: initial.getServers()) {
toKill.remove(server);
}
List<IOException> deferred = new ArrayList<IOException>();
for(ServerName sn:toStart) {
try {
if (!clusterManager.isRunning(ServiceType.HBASE_REGIONSERVER,
sn.getHostname(),
sn.getPort())
&& master.getPort() != sn.getPort()) {
LOG.info("Restoring cluster - starting initial region server: " + sn.getHostAndPort());
startRegionServer(sn.getHostname(), sn.getPort());
}
} catch (IOException ex) {
deferred.add(ex);
}
}
for(ServerName sn:toKill) {
try {
if (clusterManager.isRunning(ServiceType.HBASE_REGIONSERVER,
sn.getHostname(),
sn.getPort())
&& master.getPort() != sn.getPort()){
LOG.info("Restoring cluster - stopping initial region server: " + sn.getHostAndPort());
stopRegionServer(sn);
}
} catch (IOException ex) {
deferred.add(ex);
}
}
if (!deferred.isEmpty()) {
LOG.warn("Restoring cluster - restoring region servers reported "
+ deferred.size() + " errors:");
for (int i=0; i<deferred.size() && i < 3; i++) {
LOG.warn(deferred.get(i));
}
}
return deferred.isEmpty();
}
protected boolean restoreAdmin() throws IOException {
// While restoring above, if the HBase Master which was initially the Active one, was down
// and the restore put the cluster back to Initial configuration, HAdmin instance will need
// to refresh its connections (otherwise it will return incorrect information) or we can
// point it to new instance.
try {
admin.close();
} catch (IOException ioe) {
LOG.warn("While closing the old connection", ioe);
}
this.admin = this.connection.getAdmin();
LOG.info("Added new HBaseAdmin");
return true;
}
}
| hbase-it/src/test/java/org/apache/hadoop/hbase/DistributedHBaseCluster.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.ClusterManager.ServiceType;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ClusterConnection;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ServerInfo;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MasterService;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Threads;
/**
* Manages the interactions with an already deployed distributed cluster (as opposed to
* a pseudo-distributed, or mini/local cluster). This is used by integration and system tests.
*/
@InterfaceAudience.Private
public class DistributedHBaseCluster extends HBaseCluster {
private Admin admin;
private final Connection connection;
private ClusterManager clusterManager;
public DistributedHBaseCluster(Configuration conf, ClusterManager clusterManager)
throws IOException {
super(conf);
this.clusterManager = clusterManager;
this.connection = ConnectionFactory.createConnection(conf);
this.admin = this.connection.getAdmin();
this.initialClusterStatus = getClusterStatus();
}
public void setClusterManager(ClusterManager clusterManager) {
this.clusterManager = clusterManager;
}
public ClusterManager getClusterManager() {
return clusterManager;
}
/**
* Returns a ClusterStatus for this HBase cluster
* @throws IOException
*/
@Override
public ClusterStatus getClusterStatus() throws IOException {
return admin.getClusterStatus();
}
@Override
public ClusterStatus getInitialClusterStatus() throws IOException {
return initialClusterStatus;
}
@Override
public void close() throws IOException {
if (this.admin != null) {
admin.close();
}
if (this.connection != null && !this.connection.isClosed()) {
this.connection.close();
}
}
@Override
public AdminProtos.AdminService.BlockingInterface getAdminProtocol(ServerName serverName)
throws IOException {
return ((ClusterConnection)this.connection).getAdmin(serverName);
}
@Override
public ClientProtos.ClientService.BlockingInterface getClientProtocol(ServerName serverName)
throws IOException {
return ((ClusterConnection)this.connection).getClient(serverName);
}
@Override
public void startRegionServer(String hostname, int port) throws IOException {
LOG.info("Starting RS on: " + hostname);
clusterManager.start(ServiceType.HBASE_REGIONSERVER, hostname, port);
}
@Override
public void killRegionServer(ServerName serverName) throws IOException {
LOG.info("Aborting RS: " + serverName.getServerName());
clusterManager.kill(ServiceType.HBASE_REGIONSERVER,
serverName.getHostname(), serverName.getPort());
}
@Override
public void stopRegionServer(ServerName serverName) throws IOException {
LOG.info("Stopping RS: " + serverName.getServerName());
clusterManager.stop(ServiceType.HBASE_REGIONSERVER,
serverName.getHostname(), serverName.getPort());
}
@Override
public void waitForRegionServerToStop(ServerName serverName, long timeout) throws IOException {
waitForServiceToStop(ServiceType.HBASE_REGIONSERVER, serverName, timeout);
}
@Override
public void startZkNode(String hostname, int port) throws IOException {
LOG.info("Starting ZooKeeper node on: " + hostname);
clusterManager.start(ServiceType.ZOOKEEPER_SERVER, hostname, port);
}
@Override
public void killZkNode(ServerName serverName) throws IOException {
LOG.info("Aborting ZooKeeper node on: " + serverName.getServerName());
clusterManager.kill(ServiceType.ZOOKEEPER_SERVER,
serverName.getHostname(), serverName.getPort());
}
@Override
public void stopZkNode(ServerName serverName) throws IOException {
LOG.info("Stopping ZooKeeper node: " + serverName.getServerName());
clusterManager.stop(ServiceType.ZOOKEEPER_SERVER,
serverName.getHostname(), serverName.getPort());
}
@Override
public void waitForZkNodeToStart(ServerName serverName, long timeout) throws IOException {
waitForServiceToStart(ServiceType.ZOOKEEPER_SERVER, serverName, timeout);
}
@Override
public void waitForZkNodeToStop(ServerName serverName, long timeout) throws IOException {
waitForServiceToStop(ServiceType.ZOOKEEPER_SERVER, serverName, timeout);
}
@Override
public void startDataNode(ServerName serverName) throws IOException {
LOG.info("Starting data node on: " + serverName.getServerName());
clusterManager.start(ServiceType.HADOOP_DATANODE,
serverName.getHostname(), serverName.getPort());
}
@Override
public void killDataNode(ServerName serverName) throws IOException {
LOG.info("Aborting data node on: " + serverName.getServerName());
clusterManager.kill(ServiceType.HADOOP_DATANODE,
serverName.getHostname(), serverName.getPort());
}
@Override
public void stopDataNode(ServerName serverName) throws IOException {
LOG.info("Stopping data node on: " + serverName.getServerName());
clusterManager.stop(ServiceType.HADOOP_DATANODE,
serverName.getHostname(), serverName.getPort());
}
@Override
public void waitForDataNodeToStart(ServerName serverName, long timeout) throws IOException {
waitForServiceToStart(ServiceType.HADOOP_DATANODE, serverName, timeout);
}
@Override
public void waitForDataNodeToStop(ServerName serverName, long timeout) throws IOException {
waitForServiceToStop(ServiceType.HADOOP_DATANODE, serverName, timeout);
}
private void waitForServiceToStop(ServiceType service, ServerName serverName, long timeout)
throws IOException {
LOG.info("Waiting for service: " + service + " to stop: " + serverName.getServerName());
long start = System.currentTimeMillis();
while ((System.currentTimeMillis() - start) < timeout) {
if (!clusterManager.isRunning(service, serverName.getHostname(), serverName.getPort())) {
return;
}
Threads.sleep(100);
}
throw new IOException("did timeout waiting for service to stop:" + serverName);
}
private void waitForServiceToStart(ServiceType service, ServerName serverName, long timeout)
throws IOException {
LOG.info("Waiting for service: " + service + " to start: " + serverName.getServerName());
long start = System.currentTimeMillis();
while ((System.currentTimeMillis() - start) < timeout) {
if (clusterManager.isRunning(service, serverName.getHostname(), serverName.getPort())) {
return;
}
Threads.sleep(100);
}
throw new IOException("did timeout waiting for service to start:" + serverName);
}
@Override
public MasterService.BlockingInterface getMasterAdminService()
throws IOException {
return ((ClusterConnection)this.connection).getMaster();
}
@Override
public void startMaster(String hostname, int port) throws IOException {
LOG.info("Starting Master on: " + hostname + ":" + port);
clusterManager.start(ServiceType.HBASE_MASTER, hostname, port);
}
@Override
public void killMaster(ServerName serverName) throws IOException {
LOG.info("Aborting Master: " + serverName.getServerName());
clusterManager.kill(ServiceType.HBASE_MASTER, serverName.getHostname(), serverName.getPort());
}
@Override
public void stopMaster(ServerName serverName) throws IOException {
LOG.info("Stopping Master: " + serverName.getServerName());
clusterManager.stop(ServiceType.HBASE_MASTER, serverName.getHostname(), serverName.getPort());
}
@Override
public void waitForMasterToStop(ServerName serverName, long timeout) throws IOException {
waitForServiceToStop(ServiceType.HBASE_MASTER, serverName, timeout);
}
@Override
public boolean waitForActiveAndReadyMaster(long timeout) throws IOException {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < timeout) {
try {
getMasterAdminService();
return true;
} catch (MasterNotRunningException m) {
LOG.warn("Master not started yet " + m);
} catch (ZooKeeperConnectionException e) {
LOG.warn("Failed to connect to ZK " + e);
}
Threads.sleep(1000);
}
return false;
}
@Override
public ServerName getServerHoldingRegion(TableName tn, byte[] regionName) throws IOException {
HRegionLocation regionLoc = null;
try (RegionLocator locator = connection.getRegionLocator(tn)) {
regionLoc = locator.getRegionLocation(regionName);
}
if (regionLoc == null) {
LOG.warn("Cannot find region server holding region " + Bytes.toString(regionName) +
", start key [" + Bytes.toString(HRegionInfo.getStartKey(regionName)) + "]");
return null;
}
AdminProtos.AdminService.BlockingInterface client =
((ClusterConnection)this.connection).getAdmin(regionLoc.getServerName());
ServerInfo info = ProtobufUtil.getServerInfo(null, client);
return ProtobufUtil.toServerName(info.getServerName());
}
@Override
public void waitUntilShutDown() {
// Simply wait for a few seconds for now (after issuing serverManager.kill
throw new RuntimeException("Not implemented yet");
}
@Override
public void shutdown() throws IOException {
// not sure we want this
throw new RuntimeException("Not implemented yet");
}
@Override
public boolean isDistributedCluster() {
return true;
}
@Override
public boolean restoreClusterStatus(ClusterStatus initial) throws IOException {
ClusterStatus current = getClusterStatus();
LOG.info("Restoring cluster - started");
// do a best effort restore
boolean success = true;
success = restoreMasters(initial, current) & success;
success = restoreRegionServers(initial, current) & success;
success = restoreAdmin() & success;
LOG.info("Restoring cluster - done");
return success;
}
protected boolean restoreMasters(ClusterStatus initial, ClusterStatus current) {
List<IOException> deferred = new ArrayList<IOException>();
//check whether current master has changed
final ServerName initMaster = initial.getMaster();
if (!ServerName.isSameHostnameAndPort(initMaster, current.getMaster())) {
LOG.info("Restoring cluster - Initial active master : "
+ initMaster.getHostAndPort()
+ " has changed to : "
+ current.getMaster().getHostAndPort());
// If initial master is stopped, start it, before restoring the state.
// It will come up as a backup master, if there is already an active master.
try {
if (!clusterManager.isRunning(ServiceType.HBASE_MASTER,
initMaster.getHostname(), initMaster.getPort())) {
LOG.info("Restoring cluster - starting initial active master at:"
+ initMaster.getHostAndPort());
startMaster(initMaster.getHostname(), initMaster.getPort());
}
// master has changed, we would like to undo this.
// 1. Kill the current backups
// 2. Stop current master
// 3. Start backup masters
for (ServerName currentBackup : current.getBackupMasters()) {
if (!ServerName.isSameHostnameAndPort(currentBackup, initMaster)) {
LOG.info("Restoring cluster - stopping backup master: " + currentBackup);
stopMaster(currentBackup);
}
}
LOG.info("Restoring cluster - stopping active master: " + current.getMaster());
stopMaster(current.getMaster());
waitForActiveAndReadyMaster(); // wait so that active master takes over
} catch (IOException ex) {
// if we fail to start the initial active master, we do not want to continue stopping
// backup masters. Just keep what we have now
deferred.add(ex);
}
//start backup masters
for (ServerName backup : initial.getBackupMasters()) {
try {
//these are not started in backup mode, but we should already have an active master
if (!clusterManager.isRunning(ServiceType.HBASE_MASTER,
backup.getHostname(),
backup.getPort())) {
LOG.info("Restoring cluster - starting initial backup master: "
+ backup.getHostAndPort());
startMaster(backup.getHostname(), backup.getPort());
}
} catch (IOException ex) {
deferred.add(ex);
}
}
} else {
//current master has not changed, match up backup masters
Set<ServerName> toStart = new TreeSet<ServerName>(new ServerNameIgnoreStartCodeComparator());
Set<ServerName> toKill = new TreeSet<ServerName>(new ServerNameIgnoreStartCodeComparator());
toStart.addAll(initial.getBackupMasters());
toKill.addAll(current.getBackupMasters());
for (ServerName server : current.getBackupMasters()) {
toStart.remove(server);
}
for (ServerName server: initial.getBackupMasters()) {
toKill.remove(server);
}
for (ServerName sn:toStart) {
try {
if(!clusterManager.isRunning(ServiceType.HBASE_MASTER, sn.getHostname(), sn.getPort())) {
LOG.info("Restoring cluster - starting initial backup master: " + sn.getHostAndPort());
startMaster(sn.getHostname(), sn.getPort());
}
} catch (IOException ex) {
deferred.add(ex);
}
}
for (ServerName sn:toKill) {
try {
if(clusterManager.isRunning(ServiceType.HBASE_MASTER, sn.getHostname(), sn.getPort())) {
LOG.info("Restoring cluster - stopping backup master: " + sn.getHostAndPort());
stopMaster(sn);
}
} catch (IOException ex) {
deferred.add(ex);
}
}
}
if (!deferred.isEmpty()) {
LOG.warn("Restoring cluster - restoring region servers reported "
+ deferred.size() + " errors:");
for (int i=0; i<deferred.size() && i < 3; i++) {
LOG.warn(deferred.get(i));
}
}
return deferred.isEmpty();
}
private static class ServerNameIgnoreStartCodeComparator implements Comparator<ServerName> {
@Override
public int compare(ServerName o1, ServerName o2) {
int compare = o1.getHostname().compareToIgnoreCase(o2.getHostname());
if (compare != 0) return compare;
compare = o1.getPort() - o2.getPort();
if (compare != 0) return compare;
return 0;
}
}
protected boolean restoreRegionServers(ClusterStatus initial, ClusterStatus current) {
Set<ServerName> toStart = new TreeSet<ServerName>(new ServerNameIgnoreStartCodeComparator());
Set<ServerName> toKill = new TreeSet<ServerName>(new ServerNameIgnoreStartCodeComparator());
toStart.addAll(initial.getServers());
toKill.addAll(current.getServers());
ServerName master = initial.getMaster();
for (ServerName server : current.getServers()) {
toStart.remove(server);
}
for (ServerName server: initial.getServers()) {
toKill.remove(server);
}
List<IOException> deferred = new ArrayList<IOException>();
for(ServerName sn:toStart) {
try {
if (!clusterManager.isRunning(ServiceType.HBASE_REGIONSERVER,
sn.getHostname(),
sn.getPort())
&& master.getPort() != sn.getPort()) {
LOG.info("Restoring cluster - starting initial region server: " + sn.getHostAndPort());
startRegionServer(sn.getHostname(), sn.getPort());
}
} catch (IOException ex) {
deferred.add(ex);
}
}
for(ServerName sn:toKill) {
try {
if (clusterManager.isRunning(ServiceType.HBASE_REGIONSERVER,
sn.getHostname(),
sn.getPort())
&& master.getPort() != sn.getPort()){
LOG.info("Restoring cluster - stopping initial region server: " + sn.getHostAndPort());
stopRegionServer(sn);
}
} catch (IOException ex) {
deferred.add(ex);
}
}
if (!deferred.isEmpty()) {
LOG.warn("Restoring cluster - restoring region servers reported "
+ deferred.size() + " errors:");
for (int i=0; i<deferred.size() && i < 3; i++) {
LOG.warn(deferred.get(i));
}
}
return deferred.isEmpty();
}
protected boolean restoreAdmin() throws IOException {
// While restoring above, if the HBase Master which was initially the Active one, was down
// and the restore put the cluster back to Initial configuration, HAdmin instance will need
// to refresh its connections (otherwise it will return incorrect information) or we can
// point it to new instance.
try {
admin.close();
} catch (IOException ioe) {
LOG.warn("While closing the old connection", ioe);
}
this.admin = this.connection.getAdmin();
LOG.info("Added new HBaseAdmin");
return true;
}
}
| HBASE-17616 Incorrect actions performed by CM
Signed-off-by: tedyu <[email protected]>
| hbase-it/src/test/java/org/apache/hadoop/hbase/DistributedHBaseCluster.java | HBASE-17616 Incorrect actions performed by CM |
|
Java | apache-2.0 | d38458fda7fe8d2c2add42398a29cba19e1de544 | 0 | osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi | /*
* ============================================================================
* (c) Copyright 2004 Nokia
* This material, including documentation and any related computer programs,
* is protected by copyright controlled by Nokia and its licensors.
* All rights are reserved.
*
* These materials have been contributed to the Open Services Gateway
* Initiative (OSGi)as "MEMBER LICENSED MATERIALS" as defined in, and subject
* to the terms of, the OSGi Member Agreement specifically including, but not
* limited to, the license rights and warranty disclaimers as set forth in
* Sections 3.2 and 12.1 thereof, and the applicable Statement of Work.
* All company, brand and product names contained within this document may be
* trademarks that are the sole property of the respective owners.
* The above notice must be included on all copies of this document.
* ============================================================================
*/
package org.osgi.impl.service.dmt;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.security.*;
import java.util.*;
import info.dmtree.*;
import info.dmtree.security.*;
import info.dmtree.spi.*;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.log.LogService;
import org.osgi.service.permissionadmin.PermissionInfo;
// OPTIMIZE node handling (e.g. retrieve plugin from dispatcher only once per API call)
// OPTIMIZE only retrieve meta-data once per API call
// OPTIMIZE only call commit/rollback for plugins that were actually modified since the last transaction boundary
// TODO remove VEG CR comments, and also old code
public class DmtSessionImpl implements DmtSession {
private static final String INTERIOR_NODE_VALUE_SUPPORT_PROPERTY =
"org.osgi.impl.service.dmt.interior-node-value-support";
private static final int SHOULD_NOT_EXIST = 0;
private static final int SHOULD_EXIST = 1;
private static final int SHOULD_BE_LEAF = 2; // implies SHOULD_EXIST
private static final int SHOULD_BE_INTERIOR = 3; // implies SHOULD_EXIST
private static final Class[] PERMISSION_CONSTRUCTOR_SIG =
new Class[] { String.class, String.class };
private static Hashtable acls;
// Stores the ACL table at the start of each transaction in an atomic
// session. Can be static because atomic session cannot run in parallel.
private static Hashtable savedAcls;
static {
init_acls();
}
private final AccessControlContext securityContext;
private final DmtAdminCore dmtAdmin;
private final Context context;
private final String principal;
private final Node subtreeNode;
private final int lockMode;
private final int sessionId;
private EventStore eventStore;
private Vector dataPlugins;
private int state;
// Session creation is done in two phases:
// - DmtAdmin creates a new DmtSessionImpl instance (this should indicate
// as many errors as possible, but must not call any plugins)
// - when all conflicting sessions have been closed, DmtAdmin calls "open()"
// to actually open the session for external use
DmtSessionImpl(String principal, String subtreeUri, int lockMode,
PermissionInfo[] permissions, Context context,
DmtAdminCore dmtAdmin) throws DmtException {
Node node = Node.validateAndNormalizeUri(subtreeUri);
subtreeNode = node.isAbsolute() ?
node : Node.ROOT_NODE.appendRelativeNode(node);
this.principal = principal;
this.lockMode = lockMode;
this.dmtAdmin = dmtAdmin;
this.context = context;
if(principal != null) { // remote session
SecurityManager sm = System.getSecurityManager();
if(sm != null)
sm.checkPermission(new DmtPrincipalPermission(principal));
try {
securityContext = getSecurityContext(permissions);
} catch(Exception e) {
throw new DmtException(subtreeNode.getUri(),
DmtException.COMMAND_FAILED,
"Unable to create Protection Domain for remote server.",
e);
}
} else
securityContext = null;
sessionId =
(new Long(System.currentTimeMillis())).hashCode() ^ hashCode();
eventStore = new EventStore(context, sessionId);
dataPlugins = new Vector();
state = STATE_CLOSED;
}
// called directly before returning the session object in getSession()
// throws NODE_NOT_FOUND if the previously specified root does not exist
void open() throws DmtException {
if(lockMode == LOCK_TYPE_ATOMIC)
// shallow copy is enough, Nodes and Acls are immutable
savedAcls = (Hashtable) acls.clone();
state = STATE_OPEN;
// after everything is initialized, check with the plugins whether the
// given node really exists
checkNode(subtreeNode, SHOULD_EXIST);
eventStore.dispatchSessionLifecycleEvent(DmtEvent.SESSION_OPENED);
}
// called by Dmt Admin when checking session conflicts
Node getRootNode() {
return subtreeNode;
}
// called by the Session Wrapper, rollback parameter is:
// - true if a fatal exception has been thrown in a DMT access method
// - false if any exception has been thrown in the commit/rollback methods
protected void invalidateSession(boolean rollback, boolean timeout) {
state = STATE_INVALID;
context.log(LogService.LOG_WARNING, "Invalidating session '" +
sessionId + "' because of " + (timeout ? "timeout." : "error."),
null);
if(lockMode == LOCK_TYPE_ATOMIC && rollback) {
try {
rollbackPlugins();
} catch(DmtException e) {
context.log(LogService.LOG_WARNING, "Error rolling back " +
"plugin while invalidating session.", e);
}
}
try {
closeAndRelease(false);
} catch(DmtException e) {
context.log(LogService.LOG_WARNING, "Error closing plugin while " +
"invalidating session.", e);
}
eventStore.dispatchSessionLifecycleEvent(DmtEvent.SESSION_CLOSED);
}
/* These methods can be called even before the session has been opened, and
* also after the session has been closed. */
public synchronized int getState() {
return state;
}
public String getPrincipal() {
return principal;
}
public int getSessionId() {
return sessionId;
}
public String getRootUri() {
return subtreeNode.getUri();
}
public int getLockType() {
return lockMode;
}
/* These methods are only meaningful in the context of an open session. */
// no other API methods can be called while this method is executed
public synchronized void close() throws DmtException {
checkSession();
// changed to CLOSED if this method finishes without error
state = STATE_INVALID;
try {
closeAndRelease(lockMode == LOCK_TYPE_ATOMIC);
} finally {
eventStore.dispatchSessionLifecycleEvent(DmtEvent.SESSION_CLOSED);
}
state = STATE_CLOSED;
}
private void closeAndRelease(boolean commit) throws DmtException {
try {
if(commit)
commitPlugins();
closePlugins();
} finally {
// DmtAdmin must be notified that this session has ended, otherwise
// other sessions might never be allowed to run
dmtAdmin.releaseSession(this);
}
}
private void closePlugins() throws DmtException {
Vector closeExceptions = new Vector();
// this block requires synchronization
ListIterator i = dataPlugins.listIterator(dataPlugins.size());
while (i.hasPrevious()) {
try {
((PluginSessionWrapper) i.previous()).close();
} catch(Exception e) {
closeExceptions.add(e);
}
}
dataPlugins.clear();
if (closeExceptions.size() != 0)
throw new DmtException((String) null, DmtException.COMMAND_FAILED,
"Some plugins failed to close.", closeExceptions, false);
}
// no other API methods can be called while this method is executed
public synchronized void commit() throws DmtException {
checkSession();
if (lockMode != LOCK_TYPE_ATOMIC)
throw new IllegalStateException("Commit can only be requested " +
"for atomic sessions.");
// changed back to OPEN if this method finishes without error
state = STATE_INVALID;
commitPlugins();
savedAcls = (Hashtable) acls.clone();
state = STATE_OPEN;
}
// precondition: lockMode == LOCK_TYPE_ATOMIC
private void commitPlugins() throws DmtException {
Vector commitExceptions = new Vector();
ListIterator i = dataPlugins.listIterator(dataPlugins.size());
// this block requires synchronization
while (i.hasPrevious()) {
PluginSessionWrapper wrappedPlugin = (PluginSessionWrapper) i.previous();
try {
// checks transaction support before calling commit on the plugin
wrappedPlugin.commit();
} catch(Exception e) {
eventStore.excludeRoot(wrappedPlugin.getSessionRoot());
commitExceptions.add(e);
}
}
eventStore.dispatchEvents();
if (commitExceptions.size() != 0)
throw new DmtException((String) null,
DmtException.TRANSACTION_ERROR,
"Some plugins failed to commit.",
commitExceptions, false);
}
// no other API methods can be called while this method is executed
public synchronized void rollback() throws DmtException {
checkSession();
if (lockMode != LOCK_TYPE_ATOMIC)
throw new IllegalStateException("Rollback can only be requested " +
"for atomic sessions.");
// changed back to OPEN if this method finishes without error
state = STATE_INVALID;
acls = (Hashtable) savedAcls.clone();
rollbackPlugins();
state = STATE_OPEN;
}
// precondition: lockMode == LOCK_TYPE_ATOMIC
private void rollbackPlugins() throws DmtException {
eventStore.clear();
Vector rollbackExceptions = new Vector();
// this block requires synchronization
ListIterator i = dataPlugins.listIterator(dataPlugins.size());
while (i.hasPrevious()) {
try {
// checks transaction support before calling rollback on the plugin
((PluginSessionWrapper) i.previous()).rollback();
} catch(Exception e) {
rollbackExceptions.add(e);
}
}
if (rollbackExceptions.size() != 0)
throw new DmtException((String) null, DmtException.ROLLBACK_FAILED,
"Some plugins failed to roll back or close.",
rollbackExceptions, false);
}
public synchronized void execute(String nodeUri, String data)
throws DmtException {
internalExecute(nodeUri, null, data);
}
public synchronized void execute(String nodeUri, String correlator,
String data) throws DmtException {
internalExecute(nodeUri, correlator, data);
}
// same as execute/3 but can be called internally, because it is not wrapped
private void internalExecute(String nodeUri, final String correlator,
final String data) throws DmtException {
checkWriteSession("execute");
// not allowing to execute non-existent nodes, all Management Objects
// defined in the spec have data plugins backing them
final Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.EXEC, MetaNode.CMD_EXECUTE);
final ExecPlugin plugin =
context.getPluginDispatcher().getExecPlugin(node);
final DmtSession session = this;
if (plugin == null)
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"No exec plugin registered for given node.");
try {
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws DmtException {
plugin.execute(session, node.getPath(), correlator, data);
return null;
}
}, securityContext);
} catch(PrivilegedActionException e) {
throw (DmtException) e.getException();
}
}
// requires DmtPermission with GET action, no ACL check done because there
// are no ACLs stored for non-existing nodes (in theory)
public synchronized boolean isNodeUri(String nodeUri) {
checkSession();
try {
Node node = makeAbsoluteUri(nodeUri);
checkLocalPermission(node, writeAclCommands(Acl.GET));
checkNode(node, SHOULD_EXIST);
// not checking meta-data for the GET capability, the plugin must be
// prepared to answer isNodeUri() even if the node is not "gettable"
} catch (DmtException e) {
return false; // invalid node URI or error opening plugin
}
return true;
}
public synchronized boolean isLeafNode(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return isLeafNodeNoCheck(node);
}
// GET property op
public synchronized Acl getNodeAcl(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
Acl acl = (Acl) acls.get(node);
return acl == null ? null : acl;
}
// GET property op
public synchronized Acl getEffectiveNodeAcl(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getEffectiveNodeAclNoCheck(node);
}
// REPLACE property op
public synchronized void setNodeAcl(String nodeUri, Acl acl)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
// check for REPLACE permission:
if (isLeafNodeNoCheck(node)) // on the parent node for leaf nodes
checkNodePermission(node.getParent(), Acl.REPLACE);
else // on the node itself or the parent for interior nodes (parent will
// be ignored in case of the root node)
checkNodeOrParentPermission(node, Acl.REPLACE);
// Not checking REPLACE capability, node does not have to be modifiable
// to have an ACL associated with it. It should be possible to set
// ACLs everywhere, and the "Replace" Access Type seems to be given
// only for modifiable nodes.
// check that the new ACL is valid
if(node.isRoot() && (acl == null || !acl.isPermitted("*", Acl.ADD)))
// should be 405 "Forbidden" according to DMTND 7.7.1.2
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED, "Root ACL must allow " +
"the Add operation for all principals.");
if (acl == null || isEmptyAcl(acl))
acls.remove(node);
else
acls.put(node, acl);
getReadableDataSession(node).nodeChanged(node.getPath());
enqueueEventWithCurrentAcl(DmtEvent.REPLACED, node, null);
}
public synchronized MetaNode getMetaNode(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
checkNodePermission(node, Acl.GET);
// not checking meta-data for the GET capability, meta-data should
// always be publicly available
return getMetaNodeNoCheck(node);
}
public synchronized DmtData getNodeValue(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
return internalGetNodeValue(node);
}
// also used by copy() to pass an already validated Node instead of a URI
private DmtData internalGetNodeValue(Node node) throws DmtException {
// VEG CR supporting values for interior nodes
checkNode(node, SHOULD_EXIST);
//checkNode(node, SHOULD_BE_LEAF);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
// VEG CR supporting values for interior nodes
if(!isLeafNodeNoCheck(node)) {
checkDescendantGetPermissions(node);
checkInteriorNodeValueSupport(node);
}
ReadableDataSession pluginSession = getReadableDataSession(node);
DmtData data = pluginSession.getNodeValue(node.getPath());
// VEG CR supporting values for interior nodes
boolean isLeafNode = pluginSession.isLeafNode(node.getPath());
boolean isLeafData = data.getFormat() != DmtData.FORMAT_NODE;
if(isLeafNode != isLeafData)
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"Error retrieving node value, the type of the data " +
"returned by the plugin does not match the node type.");
return data;
}
// VEG CR supporting values for interior nodes
private void checkDescendantGetPermissions(Node node) throws DmtException {
checkNodePermission(node, Acl.GET);
if (!isLeafNodeNoCheck(node)) {
String[] children = internalGetChildNodeNames(node);
// 'children' is [] if there are no child nodes
for (int i = 0; i < children.length; i++)
checkDescendantGetPermissions(node.appendSegment(children[i]));
}
}
public synchronized String[] getChildNodeNames(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
return internalGetChildNodeNames(node);
}
// also used by copy() to pass an already validated Node instead of a URI
private String[] internalGetChildNodeNames(Node node) throws DmtException {
checkNode(node, SHOULD_BE_INTERIOR);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
String[] pluginChildNodes =
getReadableDataSession(node).getChildNodeNames(node.getPath());
List processedChildNodes = normalizeChildNodeNames(pluginChildNodes);
String[] processedChildNodeArray = (String[])
processedChildNodes.toArray(new String[processedChildNodes.size()]);
// ordering is not a requirement, but allows easier testing of plugins
Arrays.sort(processedChildNodeArray);
return processedChildNodeArray;
}
// GET property op
public synchronized String getNodeTitle(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
return internalGetNodeTitle(node);
}
// also used by copy() to pass an already validated Node instead of a URI
private String internalGetNodeTitle(Node node) throws DmtException {
checkNode(node, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeTitle(node.getPath());
}
// GET property op
public synchronized int getNodeVersion(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeVersion(node.getPath());
}
// GET property op
public synchronized Date getNodeTimestamp(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeTimestamp(node.getPath());
}
// GET property op
public synchronized int getNodeSize(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_BE_LEAF);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeSize(node.getPath());
}
// GET property op
public synchronized String getNodeType(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
return internalGetNodeType(node);
}
// also used by copy() to pass an already validated Node instead of a URI
private String internalGetNodeType(Node node) throws DmtException {
checkNode(node, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeType(node.getPath());
}
// REPLACE property op
public synchronized void setNodeTitle(String nodeUri, String title)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
internalSetNodeTitle(node, title, true); // send event if successful
}
// also used by copy() to pass an already validated Node instead of a URI
// and to set the node title without triggering an event
private void internalSetNodeTitle(Node node, String title,
boolean sendEvent) throws DmtException {
checkNode(node, SHOULD_EXIST);
checkOperation(node, Acl.REPLACE, MetaNode.CMD_REPLACE);
try {
if (title != null && title.getBytes("UTF-8").length > 255)
throw new DmtException(node.getUri(),
DmtException.COMMAND_FAILED,
"Length of Title property exceeds 255 bytes (UTF-8).");
} catch (UnsupportedEncodingException e) {
// never happens
}
getReadWriteDataSession(node).setNodeTitle(node.getPath(), title);
if(sendEvent)
enqueueEventWithCurrentAcl(DmtEvent.REPLACED, node, null);
}
public synchronized void setNodeValue(String nodeUri, DmtData data)
throws DmtException {
commonSetNodeValue(nodeUri, data);
}
public synchronized void setDefaultNodeValue(String nodeUri)
throws DmtException {
commonSetNodeValue(nodeUri, null);
}
private void commonSetNodeValue(String nodeUri, DmtData data)
throws DmtException {
checkWriteSession();
// VEG CR supporting values for interior nodes
int nodeConstraint =
data == null ? SHOULD_EXIST :
data.getFormat() == DmtData.FORMAT_NODE ?
SHOULD_BE_INTERIOR : SHOULD_BE_LEAF;
//int nodeConstraint = SHOULD_BE_LEAF;
Node node = makeAbsoluteUriAndCheck(nodeUri, nodeConstraint);
checkOperation(node, Acl.REPLACE, MetaNode.CMD_REPLACE);
// VEG CR supporting values for interior nodes
if(!isLeafNodeNoCheck(node))
checkInteriorNodeValueSupport(node);
// check data against meta-data
checkValue(node, data);
MetaNode metaNode = getMetaNodeNoCheck(node);
if (metaNode != null && metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(), DmtException.METADATA_MISMATCH,
"Cannot set the value of a permanent node.");
getReadWriteDataSession(node).setNodeValue(node.getPath(), data);
// VEG CR supporting values for interior nodes
traverseEvents(DmtEvent.REPLACED, node);
//enqueueEvent(DmtEvent.REPLACED, node);
}
// VEG CR supporting values for interior nodes
private void traverseEvents(int mode, Node node) throws DmtException {
if(isLeafNodeNoCheck(node))
enqueueEventWithCurrentAcl(mode, node, null);
else {
String children[] = internalGetChildNodeNames(node);
Arrays.sort(children);
for (int i = 0; i < children.length; i++)
traverseEvents(mode, node.appendSegment(children[i]));
}
}
// SyncML DMTND 7.5 (p16) Type: only the Get command is applicable!
public synchronized void setNodeType(String nodeUri, String type)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.REPLACE, MetaNode.CMD_REPLACE);
MetaNode metaNode = getMetaNodeNoCheck(node);
if (metaNode != null && metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(), DmtException.METADATA_MISMATCH,
"Cannot set type property of permanent node.");
if(isLeafNodeNoCheck(node))
checkMimeType(node, type);
// could check type string for interior nodes, but this impl. does not
// handle it anyway, so we leave it to the plugins if they need it
// (same in createInteriorNode/2)
getReadWriteDataSession(node).setNodeType(node.getPath(), type);
enqueueEventWithCurrentAcl(DmtEvent.REPLACED, node, null);
}
public synchronized void deleteNode(String nodeUri) throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
// sub-case of the next check, but gives a more specific error
if(node.isRoot())
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"Cannot delete root node.");
if(node.equals(subtreeNode))
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"Cannot delete root node of the session.");
checkOperation(node, Acl.DELETE, MetaNode.CMD_DELETE);
MetaNode metaNode = getMetaNodeNoCheck(node);
if (metaNode != null) {
if(metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot delete permanent node.");
if(!metaNode.isZeroOccurrenceAllowed()) {
// maxOccurrence == 1 means that there cannot be other instances
// of this node, so it cannot be deleted. If maxOccurrence > 1
// then we have to check whether this is the last one.
if(metaNode.getMaxOccurrence() == 1)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Metadata does not allow deleting the only " +
"instance of this node.");
checkNodeIsInSession(node.getParent(), "(needed to determine" +
"the number of siblings of the given node) ");
if(getNodeCardinality(node) == 1)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Metadata does not allow deleting the last " +
"instance of this node.");
}
}
getReadWriteDataSession(node).deleteNode(node.getPath());
Acl acl = getEffectiveNodeAclNoCheck(node);
moveAclEntries(node, null);
enqueueEvent(DmtEvent.DELETED, node, null, acl);
}
public synchronized void createInteriorNode(String nodeUri)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateInteriorNode(node, null, true, false);
}
public synchronized void createInteriorNode(String nodeUri, String type)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateInteriorNode(node, type, true, false);
}
// - used by the other createInteriorNode variants
// - also used by copy() to pass an already validated Node instead of a URI
// and to create interior nodes without triggering an event
// - also used by ensureInteriorAncestors, to create missing nodes while
// skipping automatically created nodes
private void commonCreateInteriorNode(Node node, String type,
boolean sendEvent, boolean skipAutomatic) throws DmtException {
checkNode(node, SHOULD_NOT_EXIST);
Node parent = node.getParent();
if(parent == null) // this should never happen, root must always exist
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"Cannot create root node.");
// Return silently if all of the following conditions are met:
// - the parent node has been created while ensuring that the ancestor
// nodes all exist
// - this call is part of creating the ancestors for some sub-node (as
// indicated by 'skipAutomatic')
// - this current node was created automatically, triggered by the
// creation of the parent (i.e. it has AUTOMATIC scope)
if(ensureInteriorAncestors(parent, sendEvent) && skipAutomatic &&
getReadableDataSession(node).isNodeUri(node.getPath()))
return;
checkNodePermission(parent, Acl.ADD);
checkNodeCapability(node, MetaNode.CMD_ADD);
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode != null && metaNode.isLeaf())
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot create the specified interior node, " +
"meta-data defines it as a leaf node.");
// could check type string, but this impl. does not handle it anyway
// so we leave it to the plugins if they need it (same in setNodeType)
checkNewNode(node);
checkMaxOccurrence(node);
// it is not really useful to allow creating automatic nodes, but this
// is not a hard requirement, and should be enforced by the (lack of
// the) ADD access type instead
getReadWriteDataSession(node).createInteriorNode(node.getPath(), type);
assignNewNodePermissions(node, parent);
if(sendEvent)
enqueueEventWithCurrentAcl(DmtEvent.ADDED, node, null);
}
public synchronized void createLeafNode(String nodeUri) throws DmtException {
// not calling createLeafNode/3, because it is wrapped
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateLeafNode(node, null, null, true);
}
public synchronized void createLeafNode(String nodeUri, DmtData value)
throws DmtException {
// not calling createLeafNode/3, because it is wrapped
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateLeafNode(node, value, null, true);
}
public synchronized void createLeafNode(String nodeUri, DmtData value,
String mimeType) throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateLeafNode(node, value, mimeType, true);
}
// - used by the other createLeafNode variants
// - also used by copy() to pass an already validated Node instead of a URI
// and to create leaf nodes without triggering an event
private void commonCreateLeafNode(Node node, DmtData value,
String mimeType, boolean sendEvent) throws DmtException {
checkNode(node, SHOULD_NOT_EXIST);
Node parent = node.getParent();
if(parent == null) // this should never happen, root must always exist
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"Cannot create root node.");
ensureInteriorAncestors(parent, sendEvent);
checkNodePermission(parent, Acl.ADD);
checkNodeCapability(node, MetaNode.CMD_ADD);
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode != null && !metaNode.isLeaf())
throw new DmtException(node.getUri(), DmtException.METADATA_MISMATCH,
"Cannot create the specified leaf node, meta-data " +
"defines it as an interior node.");
checkNewNode(node);
checkValue(node, value);
checkMimeType(node, mimeType);
checkMaxOccurrence(node);
// it is not really useful to allow creating automatic nodes, but this
// is not a hard requirement, and should be enforced by the (lack of
// the) ADD access type instead
getReadWriteDataSession(node).createLeafNode(node.getPath(), value,
mimeType);
if(sendEvent)
enqueueEventWithCurrentAcl(DmtEvent.ADDED, node, null);
}
// Tree may be left in an inconsistent state if there is an error when only
// part of the tree has been copied.
public synchronized void copy(String nodeUri, String newNodeUri,
boolean recursive) throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
Node newNode = makeAbsoluteUriAndCheck(newNodeUri, SHOULD_NOT_EXIST);
if (node.isAncestorOf(newNode))
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"Cannot copy node to its descendant, '" + newNode + "'.");
if (context.getPluginDispatcher()
.handledBySameDataPlugin(node, newNode)) {
Node newParentNode = newNode.getParent();
// newParentNode cannot be null, because newNode is a valid absolute
// nonexisting node, so it cannot be the root
ensureInteriorAncestors(newParentNode, false);
// DMTND 7.7.1.5: "needs correct access rights for the equivalent
// Add, Delete, Get, and Replace commands"
copyPermissionCheck(node, newParentNode, newNode, recursive);
checkNodeCapability(node, MetaNode.CMD_GET);
checkNodeCapability(newNode, MetaNode.CMD_ADD);
checkNewNode(newNode);
checkMaxOccurrence(newNode);
// for leaf nodes: since we are not passing a data object to the
// plugin, checking the value and mime-type against the new
// meta-data is the responsibility of the plugin itself
try {
getReadWriteDataSession(newNode).copy(node.getPath(),
newNode.getPath(), recursive);
assignNewNodePermissions(newNode, newParentNode);
} catch(DmtException e) {
// fall back to generic algorithm if plugin doesn't support copy
if(e.getCode() != DmtException.FEATURE_NOT_SUPPORTED)
throw e;
// the above checks will be performed again, but we cannot even
// attempt to call the plugin without them
copyNoCheck(node, newNode, recursive);
}
}
else
copyNoCheck(node, newNode, recursive); // does not trigger events
Acl acl = getEffectiveNodeAclNoCheck(node);
Acl newAcl = getEffectiveNodeAclNoCheck(newNode);
Acl mergedAcl = mergeAcls(acl, newAcl);
enqueueEvent(DmtEvent.COPIED, node, newNode, mergedAcl);
}
public synchronized void renameNode(String nodeUri, String newNodeName)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.REPLACE, MetaNode.CMD_REPLACE);
Node parent = node.getParent();
// sub-case of the next check, but gives a more specific error
if (parent == null)
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"Cannot rename root node.");
if(node.equals(subtreeNode))
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"Cannot rename root node of the session.");
String newName = Node.validateAndNormalizeNodeName(newNodeName);
Node newNode = parent.appendSegment(newName);
checkNode(newNode, SHOULD_NOT_EXIST);
checkNewNode(newNode);
MetaNode metaNode = getMetaNodeNoCheck(node);
MetaNode newMetaNode = getMetaNodeNoCheck(newNode);
if (metaNode != null) {
if(metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot rename permanent node.");
int maxOcc = metaNode.getMaxOccurrence();
// sanity check: all siblings of a node must either have a
// cardinality of 1, or they must be part of the same multi-node
if(newMetaNode != null && maxOcc != newMetaNode.getMaxOccurrence())
throw new DmtException(node.getUri(),
DmtException.COMMAND_FAILED,
"Cannot rename node, illegal meta-data found (a " +
"member of a multi-node has a sibling with different " +
"meta-data).");
// if this is a multi-node (maxOcc > 1), renaming does not affect
// the cardinality
if(maxOcc == 1 && !metaNode.isZeroOccurrenceAllowed())
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Metadata does not allow deleting last instance of " +
"this node.");
}
// the new node must be the same (leaf/interior) as the original
if(newMetaNode != null && newMetaNode.isLeaf() != isLeafNodeNoCheck(node))
throw new DmtException(newNode.getUri(),
DmtException.METADATA_MISMATCH,
"The destination of the rename operation is " +
(newMetaNode.isLeaf() ? "a leaf" : "an interior") +
" node according to the meta-data, which does not match " +
"the source node.");
// for leaf nodes: since we are not passing a data object to the
// plugin, checking the value and mime-type against the new
// meta-data is the responsibility of the plugin itself
getReadWriteDataSession(node).renameNode(node.getPath(), newName);
Acl acl = getEffectiveNodeAclNoCheck(node);
moveAclEntries(node, newNode);
enqueueEvent(DmtEvent.RENAMED, node, newNode, acl);
}
/**
* Create an Access Control Context based on the given permissions. The
* Permission objects are first created from the PermissionInfo objects,
* then added to a permission collection, which is added to a protection
* domain with no code source, which is used to create the access control
* context. If the <code>null</code> argument is given, an empty access
* control context is created.
*
* @throws Exception if there is an error creating one of the permission
* objects (can be one of ClassNotFoundException, SecurityException,
* NoSuchMethodException, ClassCastException,
* IllegalArgumentException, InstantiationException,
* IllegalAccessException or InvocationTargetException)
*/
private AccessControlContext getSecurityContext(PermissionInfo[] permissions)
throws Exception {
PermissionCollection permissionCollection = new Permissions();
if(permissions != null)
for (int i = 0; i < permissions.length; i++) {
PermissionInfo info = permissions[i];
Class permissionClass = Class.forName(info.getType());
Constructor constructor = permissionClass
.getConstructor(PERMISSION_CONSTRUCTOR_SIG);
Permission permission = (Permission) constructor.newInstance(
new Object[] {info.getName(), info.getActions()});
permissionCollection.add(permission);
}
return new AccessControlContext(new ProtectionDomain[] {
new ProtectionDomain(null, permissionCollection)});
}
private void checkSession() {
if(state != STATE_OPEN)
throw new IllegalStateException(
"Session is not open, cannot perform DMT operations.");
}
private void checkWriteSession() {
checkWriteSession("write");
}
private void checkWriteSession(String op) {
checkSession();
if(lockMode == LOCK_TYPE_SHARED)
throw new IllegalStateException(
"Session is not open for writing, cannot perform " +
"requested " + op + " operation.");
}
private Acl mergeAcls(Acl acl1, Acl acl2) {
Acl mergedAcl = acl1;
String[] principals = acl2.getPrincipals();
for (int i = 0; i < principals.length; i++)
mergedAcl = mergedAcl.addPermission(principals[i], acl2
.getPermissions(principals[i]));
mergedAcl.addPermission("*", acl2.getPermissions("*"));
return mergedAcl;
}
private void enqueueEventWithCurrentAcl(int type, Node node, Node newNode) {
Acl acl = null;
if(node != null)
acl = getEffectiveNodeAclNoCheck(node);
enqueueEvent(type, node, newNode, acl);
}
private void enqueueEvent(int type, Node node, Node newNode, Acl acl) {
boolean isAtomic = lockMode == LOCK_TYPE_ATOMIC;
eventStore.add(type, node, newNode, acl, isAtomic);
}
private boolean isLeafNodeNoCheck(Node node) throws DmtException {
return getReadableDataSession(node).isLeafNode(node.getPath());
}
private MetaNode getMetaNodeNoCheck(Node node) throws DmtException {
return getReadableDataSession(node).getMetaNode(node.getPath());
}
// precondition: 'uri' must point be valid (checked with isNodeUri or
// returned by getChildNodeNames)
private void copyNoCheck(Node node, Node newNode, boolean recursive)
throws DmtException {
boolean isLeaf = isLeafNodeNoCheck(node);
String type = internalGetNodeType(node);
// create new node (without sending a separate event about it)
if (isLeaf)
// if getNodeValue() returns null, we attempt to set the default
commonCreateLeafNode(newNode, internalGetNodeValue(node), type,
false);
else
commonCreateInteriorNode(newNode, type, false, false);
// copy Title property (without sending event) if it is supported by
// both source and target plugins
try {
String title = internalGetNodeTitle(node);
// It could be valid to copy "null" Titles as well, if the
// implementation has default values for the Title property.
if(title != null)
internalSetNodeTitle(newNode, title, false);
} catch (DmtException e) {
if (e.getCode() != DmtException.FEATURE_NOT_SUPPORTED)
throw new DmtException(node.getUri(),
DmtException.COMMAND_FAILED, "Error copying node to '" +
newNode + "', cannot copy title.", e);
}
// Format, Name, Size, TStamp and VerNo properties do not need to be
// expicitly copied
// copy children if mode is recursive and node is interior
if (recursive && !isLeaf) {
// 'children' is [] if there are no child nodes
String[] children = internalGetChildNodeNames(node);
for (int i = 0; i < children.length; i++)
copyNoCheck(node.appendSegment(children[i]),
newNode.appendSegment(children[i]), true);
}
}
// precondition: path must be absolute, and the parent of the given node
// must be within the subtree of the session
private int getNodeCardinality(Node node) throws DmtException {
Node parent = node.getParent();
String[] neighbours =
getReadableDataSession(parent).getChildNodeNames(parent.getPath());
return normalizeChildNodeNames(neighbours).size();
}
private void assignNewNodePermissions(Node node, Node parent)
throws DmtException {
// DMTND 7.7.1.3: if parent does not have Replace permissions, give Add,
// Delete and Replace permissions to child. (This rule cannot be
// applied to Java permissions, only to ACLs.)
if(principal != null) {
try {
checkNodePermission(parent, Acl.REPLACE);
} catch (DmtException e) {
if (e.getCode() != DmtException.PERMISSION_DENIED)
throw e; // should not happen
Acl parentAcl = getEffectiveNodeAclNoCheck(parent);
Acl newAcl = parentAcl.addPermission(principal, Acl.ADD
| Acl.DELETE | Acl.REPLACE);
acls.put(node, newAcl);
}
}
}
private void checkOperation(Node node, int actions, int capability)
throws DmtException {
checkNodePermission(node, actions);
checkNodeCapability(node, capability);
}
// throws SecurityException if principal is local user, and sufficient
// privileges are missing
private void checkNodePermission(Node node, int actions)
throws DmtException {
checkNodeOrParentPermission(principal, node, actions, false);
}
// throws SecurityException if principal is local user, and sufficient
// privileges are missing
private void checkNodeOrParentPermission(Node node, int actions)
throws DmtException {
checkNodeOrParentPermission(principal, node, actions, true);
}
// Performs the necessary permission checks for a copy operation:
// - checks that the caller has GET rights (ACL or Java permission) for all
// source nodes
// - in case of local sessions, checks that the caller has REPLACE Java
// permissions on all nodes where a title needs to be set, and ADD Java
// permissions for the parents of all added nodes
// - in case of remote sessions, only the ACL of the parent of the target
// node needs to be checked, because ACLs cannot be set for nonexitent
// nodes; in this case the ADD ACL is always required, while REPLACE is
// checked only if any of the copied nodes has a non-null Title string
//
// Precondition: 'node' must point be valid (checked with isNodeUri or
// returned by getChildNodeNames)
private void copyPermissionCheck(Node node, Node newParentNode,
Node newNode, boolean recursive) throws DmtException {
boolean hasTitle = copyPermissionCheckRecursive(node, newParentNode,
newNode, recursive);
// ACL not copied, so the parent of the target node only needs
// REPLACE permission if the copied node (or any node in the copied
// subtree) has a title
// remote access permissions for the target only need to be checked once
if(principal != null) {
checkNodePermission(newParentNode, Acl.ADD);
if(hasTitle)
checkNodePermission(newNode, Acl.REPLACE);
}
}
private boolean copyPermissionCheckRecursive(Node node,
Node newParentNode, Node newNode, boolean recursive)
throws DmtException {
// check that the caller has GET rights for the current node
checkNodePermission(node, Acl.GET);
// check whether the node has a non-null title
boolean hasTitle = nodeHasTitle(node);
// local access permissions need to be checked for each target node
if(principal == null) {
checkLocalPermission(newParentNode, writeAclCommands(Acl.ADD));
if(hasTitle)
checkLocalPermission(newNode, writeAclCommands(Acl.REPLACE));
}
// perform the checks recursively for the subtree if requested
if (recursive && !isLeafNodeNoCheck(node)) {
// 'children' is [] if there are no child nodes
String[] children = internalGetChildNodeNames(node);
for (int i = 0; i < children.length; i++)
if(copyPermissionCheckRecursive(node.appendSegment(children[i]),
newNode, newNode.appendSegment(children[i]), true))
hasTitle = true;
}
return hasTitle;
}
// Returns true if the plugin handling the given node supports the Title
// property and value of the property is non-null. This is used for
// determining whether the caller needs to have REPLACE rights for the
// target node of the enclosing copy operation.
private boolean nodeHasTitle(Node node) throws DmtException {
try {
return internalGetNodeTitle(node) != null;
} catch (DmtException e) {
// FEATURE_NOT_SUPPORTED means that Title is not supported
if (e.getCode() != DmtException.FEATURE_NOT_SUPPORTED)
throw e;
}
return false;
}
private Node makeAbsoluteUriAndCheck(String nodeUri, int check)
throws DmtException {
Node node = makeAbsoluteUri(nodeUri);
checkNode(node, check);
return node;
}
// returns a plugin for read-only use
private ReadableDataSession getReadableDataSession(Node node)
throws DmtException {
return getPluginSession(node, false);
}
// returns a plugin for writing
private ReadWriteDataSession getReadWriteDataSession(Node node)
throws DmtException {
return getPluginSession(node, true);
}
// precondition: if 'writable' is true, session lock type must not be shared
// 'synchronized' is just indication, all entry points are synch'd anyway
private synchronized PluginSessionWrapper getPluginSession(Node node,
boolean writeOperation) throws DmtException {
PluginSessionWrapper wrappedPlugin = null;
Node wrappedPluginRoot = null;
// Look through the open plugin sessions, and find the session with the
// lowest root that handles the given node.
Iterator i = dataPlugins.iterator();
while (i.hasNext()) {
PluginSessionWrapper plugin = (PluginSessionWrapper) i.next();
Node pluginRoot = plugin.getSessionRoot();
if(pluginRoot.isAncestorOf(node) && (wrappedPluginRoot == null ||
wrappedPluginRoot.isAncestorOf(pluginRoot))) {
wrappedPlugin = plugin;
wrappedPluginRoot = pluginRoot;
}
}
// Find the plugin that would/will handle the given node, and the root
// of the (potential) session opened on it.
PluginRegistration pluginRegistration =
context.getPluginDispatcher().getDataPlugin(node);
Node root = getRootForPlugin(pluginRegistration, node);
// If we found a plugin session handling the node, and the potential
// new plugin session root (defined by 'root') is not in its subtree,
// then use the open session. If there is no session yet, or if a new
// session could be opened with a deeper root, then a new session is
// opened. (This guarantees that the proper plugin is used instead of
// the root plugin for nodes below the "root tree".)
if(wrappedPlugin != null &&
!wrappedPluginRoot.isAncestorOf(root, true)) {
if(writeOperation &&
wrappedPlugin.getSessionType() == LOCK_TYPE_SHARED)
throw getWriteException(lockMode, node);
return wrappedPlugin;
}
// No previously opened session found, attempting to open session with
// correct lock type.
DataPlugin plugin = pluginRegistration.getDataPlugin();
ReadableDataSession pluginSession = null;
int pluginSessionType = lockMode;
if(lockMode != LOCK_TYPE_SHARED) {
pluginSession = openPluginSession(plugin, root, pluginSessionType);
if(pluginSession == null && writeOperation)
throw getWriteException(lockMode, node);
}
// read-only session if lockMode is LOCK_TYPE_SHARED, or if the
// plugin did not support the writing lock mode, and the current
// operation is for reading
if(pluginSession == null) {
pluginSessionType = LOCK_TYPE_SHARED;
pluginSession = openPluginSession(plugin, root, pluginSessionType);
}
wrappedPlugin = new PluginSessionWrapper(pluginRegistration,
pluginSession, pluginSessionType, root, securityContext);
// this requires synchronized access
dataPlugins.add(wrappedPlugin);
return wrappedPlugin;
}
private Node getRootForPlugin(PluginRegistration plugin, Node node) {
Node[] roots = plugin.getDataRoots();
for(int i = 0; i < roots.length; i++)
if(roots[i].isAncestorOf(node))
return roots[i].isAncestorOf(subtreeNode)
? subtreeNode : roots[i];
throw new IllegalStateException("Internal error, plugin root not " +
"found for a URI handled by the plugin.");
}
private ReadableDataSession openPluginSession(
final DataPlugin plugin, Node root,
final int pluginSessionType) throws DmtException {
final DmtSession session = this;
final String[] rootPath = root.getPath();
ReadableDataSession pluginSession;
try {
pluginSession = (ReadableDataSession)
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws DmtException {
switch(pluginSessionType) {
case LOCK_TYPE_EXCLUSIVE:
return plugin.openReadWriteSession(rootPath, session);
case LOCK_TYPE_ATOMIC:
return plugin.openAtomicSession(rootPath, session);
default: // LOCK_TYPE_SHARED
return plugin.openReadOnlySession(rootPath, session);
}
}
}, securityContext);
} catch(PrivilegedActionException e) {
throw (DmtException) e.getException();
}
return pluginSession;
}
// precondition: path must be absolute
private void checkNode(Node node, int check) throws DmtException {
boolean shouldExist = (check != SHOULD_NOT_EXIST);
if (getReadableDataSession(node).isNodeUri(node.getPath()) != shouldExist)
throw new DmtException(node.getUri(),
shouldExist ? DmtException.NODE_NOT_FOUND
: DmtException.NODE_ALREADY_EXISTS,
"The specified URI should point to "
+ (shouldExist ? "an existing" : "a non-existent")
+ " node to perform the requested operation.");
boolean shouldBeLeaf = (check == SHOULD_BE_LEAF);
boolean shouldBeInterior = (check == SHOULD_BE_INTERIOR);
if ((shouldBeLeaf || shouldBeInterior)
&& isLeafNodeNoCheck(node) != shouldBeLeaf)
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"The specified URI should point to "
+ (shouldBeLeaf ? "a leaf" : "an internal")
+ " node to perform the requested operation.");
}
// precondition: checkNode() must have been called for the given uri
private void checkNodeCapability(Node node, int capability)
throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode != null && !metaNode.can(capability))
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Node meta-data does not allow the " +
capabilityName(capability) + " operation for this node.");
// default for all capabilities is 'true', if no meta-data is provided
}
private void checkValue(Node node, DmtData data) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
// if default data was requested, only check that there is a default
if(data == null) {
if(metaNode.getDefault() == null)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"This node has no default value in the meta-data.");
return;
}
if(!metaNode.isValidValue(data))
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"The specified node value is not valid according to " +
"the meta-data.");
// not checking value meta-data constraints individually, but leaving
// this to the isValidValue method of the meta-node
/*
if((metaNode.getFormat() & data.getFormat()) == 0)
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"The format of the specified value is not in the list of " +
"valid formats given in the node meta-data.");
if(data.getFormat() == DmtData.FORMAT_INTEGER) {
if(metaNode.getMax() < data.getInt())
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"Attempting to set too large integer, meta-data " +
"specifies the maximum value of " + metaNode.getMax());
if(metaNode.getMin() > data.getInt())
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"Attempting to set too small integer, meta-data " +
"specifies the minimum value of " + metaNode.getMin());
}
DmtData[] validValues = metaNode.getValidValues();
if(validValues != null && !Arrays.asList(validValues).contains(data))
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"Specified value is not in the list of valid values " +
"given in the node meta-data.");
*/
}
// precondition: path must be absolute and must specify an interior node
private void checkInteriorNodeValueSupport(Node node) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
boolean interiorNodeValueSupported = true;
try {
interiorNodeValueSupported = ((Boolean) metaNode
.getExtensionProperty(INTERIOR_NODE_VALUE_SUPPORT_PROPERTY))
.booleanValue();
} catch(IllegalArgumentException e) {
} catch(ClassCastException e) {
}
if(!interiorNodeValueSupported)
throw new DmtException(node.getUri(),
DmtException.FEATURE_NOT_SUPPORTED, "The given interior " +
"node does not support complex java values.");
}
private void checkNewNode(Node node) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
if(metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot create permanent node.");
if(!metaNode.isValidName(node.getLastSegment()))
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"The specified node name is not valid according to " +
"the meta-data.");
// not checking valid name list from meta-data, but leaving this to the
// isValidName method of the meta-node
/*
String[] validNames = metaNode.getValidNames();
if(validNames != null && !Arrays.asList(validNames).contains(name))
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"The specified node name is not in the list of valid " +
"names specified in the node meta-data.");
*/
}
private void checkMimeType(Node node, String type) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
if(type == null) // default MIME type was requested
return;
int sep = type.indexOf('/');
if(sep == -1 || sep == 0 || sep == type.length()-1)
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"The given type string does not contain a MIME type.");
String[] validMimeTypes = metaNode.getMimeTypes();
if(validMimeTypes != null && !Arrays.asList(validMimeTypes).contains(type))
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"The specified MIME type is not in the list of valid " +
"types in the node meta-data.");
}
private void checkMaxOccurrence(Node node) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
// If maxOccurrence == 1 then it is not a multi-node, so it can be
// created if it did not exist before. If maxOccurrence > 1, it can
// only be created if the number of existing nodes does not reach it.
int maxOccurrence = metaNode.getMaxOccurrence();
if(maxOccurrence != Integer.MAX_VALUE && maxOccurrence > 1
&& getNodeCardinality(node) >= maxOccurrence)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot create the specified node, meta-data maximizes " +
"the number of instances of this node to " + maxOccurrence + ".");
}
private Node makeAbsoluteUri(String nodeUri) throws DmtException {
Node node = Node.validateAndNormalizeUri(nodeUri);
if (node.isAbsolute()) {
checkNodeIsInSession(node, "");
return node;
}
return subtreeNode.appendRelativeNode(node);
}
private void checkNodeIsInSession(Node node, String uriExplanation)
throws DmtException {
if (!subtreeNode.isAncestorOf(node))
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"Specified URI " + uriExplanation + "points outside the " +
"subtree of this session.");
}
private boolean ensureInteriorAncestors(Node node, boolean sendEvent)
throws DmtException {
checkNodeIsInSession(node, "(needed to ensure " +
"a proper creation point for the new node) ");
if (!getReadableDataSession(node).isNodeUri(node.getPath())) {
commonCreateInteriorNode(node, null, sendEvent, true);
return true;
}
checkNode(node, SHOULD_BE_INTERIOR);
return false;
}
private static DmtException getWriteException(int lockMode, Node node) {
boolean atomic = (lockMode == LOCK_TYPE_ATOMIC);
return new DmtException(node.getUri(),
atomic ? DmtException.TRANSACTION_ERROR : DmtException.COMMAND_NOT_ALLOWED,
"The plugin handling the requested node does not support " +
(atomic ? "" : "non-") + "atomic writing.");
}
// remove null entries from the returned array (if it is non-null)
private static List normalizeChildNodeNames(String[] pluginChildNodes) {
List processedChildNodes = new Vector();
if (pluginChildNodes != null)
for (int i = 0; i < pluginChildNodes.length; i++)
if (pluginChildNodes[i] != null)
processedChildNodes.add(pluginChildNodes[i]);
return processedChildNodes;
}
// Move ACL entries from 'node' to 'newNode'.
// If 'newNode' is 'null', the ACL entries are removed (moved to nowhere).
private static void moveAclEntries(Node node, Node newNode) {
synchronized (acls) {
Hashtable newEntries = null;
if (newNode != null)
newEntries = new Hashtable();
Iterator i = acls.entrySet().iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
Node relativeNode =
node.getRelativeNode((Node) entry.getKey());
if (relativeNode != null) {
if (newNode != null)
newEntries.put(newNode.appendRelativeNode(relativeNode),
entry.getValue());
i.remove();
}
}
if (newNode != null)
acls.putAll(newEntries);
}
}
private static Acl getEffectiveNodeAclNoCheck(Node node) {
Acl acl;
synchronized (acls) {
acl = (Acl) acls.get(node);
// must finish whithout NullPointerException, because root ACL must
// not be empty
while (acl == null || isEmptyAcl(acl)) {
node = node.getParent();
acl = (Acl) acls.get(node);
}
}
return acl;
}
// precondition: node parameter must be an absolute node
// throws SecurityException if principal is local user, and sufficient
// privileges are missing
private static void checkNodeOrParentPermission(String name, Node node,
int actions, boolean checkParent) throws DmtException {
if(node.isRoot())
checkParent = false;
Node parent = null;
if(checkParent) // not null, as the uri is absolute but not "."
parent = node.getParent();
if (name != null) {
// succeed if the principal has the required permissions on the
// given uri, OR if the checkParent parameter is true and the
// principal has the required permissions for the parent uri
if (!(
hasAclPermission(node, name, actions) ||
checkParent && hasAclPermission(parent, name, actions)))
throw new DmtException(node.getUri(),
DmtException.PERMISSION_DENIED, "Principal '" + name
+ "' does not have the required permissions ("
+ writeAclCommands(actions) + ") on the node "
+ (checkParent ? "or its parent " : "")
+ "to perform this operation.");
}
else { // not doing local permission check if ACL check was done
String actionString = writeAclCommands(actions);
checkLocalPermission(node, actionString);
if(checkParent)
checkLocalPermission(parent, actionString);
}
}
private static boolean hasAclPermission(Node node, String name, int actions) {
return getEffectiveNodeAclNoCheck(node).isPermitted(name, actions);
}
private static void checkLocalPermission(Node node, String actions) {
SecurityManager sm = System.getSecurityManager();
if(sm != null)
sm.checkPermission(new DmtPermission(node.getUri(), actions));
}
private static String capabilityName(int capability) {
switch(capability) {
case MetaNode.CMD_ADD: return "Add";
case MetaNode.CMD_DELETE: return "Delete";
case MetaNode.CMD_EXECUTE: return "Execute";
case MetaNode.CMD_GET: return "Get";
case MetaNode.CMD_REPLACE: return "Replace";
}
// never reached
throw new IllegalArgumentException(
"Unknown meta-data capability constant " + capability + ".");
}
private static String writeAclCommands(int actions) {
String cmds = null;
cmds = writeCommand(cmds, actions, Acl.ADD, DmtPermission.ADD);
cmds = writeCommand(cmds, actions, Acl.DELETE, DmtPermission.DELETE);
cmds = writeCommand(cmds, actions, Acl.EXEC, DmtPermission.EXEC);
cmds = writeCommand(cmds, actions, Acl.GET, DmtPermission.GET);
cmds = writeCommand(cmds, actions, Acl.REPLACE, DmtPermission.REPLACE);
return (cmds != null) ? cmds : "";
}
private static String writeCommand(String base, int actions, int action,
String entry) {
if ((actions & action) != 0)
return (base != null) ? base + ',' + entry : entry;
return base;
}
private static boolean isEmptyAcl(Acl acl) {
return acl.getPermissions("*") == 0 && acl.getPrincipals().length == 0;
}
static void init_acls() {
acls = new Hashtable();
acls.put(Node.ROOT_NODE, new Acl("Add=*&Get=*&Replace=*"));
}
public String toString() {
StringBuffer info = new StringBuffer();
info.append("DmtSessionImpl(");
info.append(principal).append(", ");
info.append(subtreeNode).append(", ");
if(lockMode == LOCK_TYPE_ATOMIC)
info.append("atomic");
else if(lockMode == LOCK_TYPE_EXCLUSIVE)
info.append("exclusive");
else
info.append("shared");
info.append(", ");
if(state == STATE_CLOSED)
info.append("closed");
else if(state == STATE_OPEN)
info.append("open");
else
info.append("invalid");
return info.append(')').toString();
}
}
// Multi-purpose event store class:
// - stores sets of node URIs for the different types of changes within an
// atomic session
// - contains a static event queue for the asynchronous local event delivery;
// this queue is emptied by DmtAdminFactory, which forwards the events to all
// locally registered DmtEventListeners
class EventStore {
private static LinkedList localEventQueue = new LinkedList();
private static void postLocalEvent(DmtEventCore event) {
synchronized (localEventQueue) {
localEventQueue.addLast(event);
localEventQueue.notifyAll();
}
}
// Retrieve the next event from the queue. If there are no events, block
// until one is added, or until the given timeout time (in milliseconds) has
// elapsed. A timeout of zero blocks indefinitely. In case of timeout, or
// if the wait has been interrupted, the method returns "null".
static DmtEventCore getNextLocalEvent(int timeout) {
synchronized (localEventQueue) {
if(localEventQueue.size() == 0) {
try {
localEventQueue.wait(timeout);
} catch (InterruptedException e) {
// do nothing
}
if(localEventQueue.size() == 0)
return null;
}
return (DmtEventCore) localEventQueue.removeFirst();
}
}
private final int sessionId;
private final Context context;
private Hashtable events;
EventStore(Context context, int sessionId) {
this.sessionId = sessionId;
this.context = context;
events = new Hashtable();
}
synchronized void clear() {
events.clear();
}
synchronized void excludeRoot(Node root) {
Enumeration e = events.elements();
while (e.hasMoreElements())
((DmtEventCore) e.nextElement()).excludeRoot(root);
}
synchronized void add(int type, Node node, Node newNode, Acl acl,
boolean isAtomic) {
if (isAtomic) { // add event to event store, for delivery at commit
Integer typeInteger = new Integer(type);
DmtEventCore event = (DmtEventCore) events.get(typeInteger);
if(event == null) {
event = new DmtEventCore(type, sessionId);
events.put(typeInteger, event);
}
event.addNode(node, newNode, acl);
} else // dispatch to local and OSGi event listeners immediately
dispatchEvent(new DmtEventCore(type, sessionId, node, newNode, acl));
}
synchronized void dispatchEvents() {
dispatchEventsByType(DmtEvent.ADDED);
dispatchEventsByType(DmtEvent.DELETED);
dispatchEventsByType(DmtEvent.REPLACED);
dispatchEventsByType(DmtEvent.RENAMED);
dispatchEventsByType(DmtEvent.COPIED);
clear();
}
synchronized void dispatchEventsByType(int type) {
DmtEventCore event = (DmtEventCore) events.get(new Integer(type));
if(event != null)
dispatchEvent(event);
}
synchronized void dispatchSessionLifecycleEvent(int type) {
if(type != DmtEvent.SESSION_OPENED && type != DmtEvent.SESSION_CLOSED)
throw new IllegalArgumentException("Invalid event type, only " +
"session lifecycle events can be dispatched directly.");
dispatchEvent(new DmtEventCore(type, sessionId));
}
private void dispatchEvent(DmtEventCore dmtEvent) {
// send event to listeners directly registered with DmtAdmin
postLocalEvent(dmtEvent);
// send event to listeners registered through EventAdmin
postOSGiEvent(dmtEvent);
}
private void postOSGiEvent(DmtEventCore dmtEvent) {
final EventAdmin eventChannel =
(EventAdmin) context.getTracker(EventAdmin.class).getService();
if(eventChannel == null) {// logging a warning if Event Admin is missing
context.log(LogService.LOG_WARNING, "Event Admin not found, only " +
"delivering events to listeners directly registered with " +
"DmtAdmin.", null);
return;
}
Hashtable properties = new Hashtable();
properties.put("session.id", new Integer(dmtEvent.getSessionId()));
List nodes = dmtEvent.getNodes();
if(nodes != null)
properties.put("nodes",
Node.getUriArray((Node[]) nodes.toArray(new Node[0])));
List newNodes = dmtEvent.getNewNodes();
if(newNodes != null)
properties.put("newnodes",
Node.getUriArray((Node[]) newNodes.toArray(new Node[0])));
final Event event = new Event(dmtEvent.getTopic(), properties);
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
eventChannel.postEvent(event);
return null;
}
});
}
}
| org.osgi.impl.service.dmt/src/org/osgi/impl/service/dmt/DmtSessionImpl.java | /*
* ============================================================================
* (c) Copyright 2004 Nokia
* This material, including documentation and any related computer programs,
* is protected by copyright controlled by Nokia and its licensors.
* All rights are reserved.
*
* These materials have been contributed to the Open Services Gateway
* Initiative (OSGi)as "MEMBER LICENSED MATERIALS" as defined in, and subject
* to the terms of, the OSGi Member Agreement specifically including, but not
* limited to, the license rights and warranty disclaimers as set forth in
* Sections 3.2 and 12.1 thereof, and the applicable Statement of Work.
* All company, brand and product names contained within this document may be
* trademarks that are the sole property of the respective owners.
* The above notice must be included on all copies of this document.
* ============================================================================
*/
package org.osgi.impl.service.dmt;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.security.*;
import java.util.*;
import info.dmtree.*;
import info.dmtree.security.*;
import info.dmtree.spi.*;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.log.LogService;
import org.osgi.service.permissionadmin.PermissionInfo;
// OPTIMIZE node handling (e.g. retrieve plugin from dispatcher only once per API call)
// OPTIMIZE only retrieve meta-data once per API call
// OPTIMIZE only call commit/rollback for plugins that were actually modified since the last transaction boundary
// TODO remove VEG CR comments, and also old code
public class DmtSessionImpl implements DmtSession {
private static final String INTERIOR_NODE_VALUE_SUPPORT_PROPERTY =
"org.osgi.impl.service.dmt.interior-node-value-support";
private static final int SHOULD_NOT_EXIST = 0;
private static final int SHOULD_EXIST = 1;
private static final int SHOULD_BE_LEAF = 2; // implies SHOULD_EXIST
private static final int SHOULD_BE_INTERIOR = 3; // implies SHOULD_EXIST
private static final Class[] PERMISSION_CONSTRUCTOR_SIG =
new Class[] { String.class, String.class };
private static Hashtable acls;
// Stores the ACL table at the start of each transaction in an atomic
// session. Can be static because atomic session cannot run in parallel.
private static Hashtable savedAcls;
static {
init_acls();
}
private final AccessControlContext securityContext;
private final DmtAdminCore dmtAdmin;
private final Context context;
private final String principal;
private final Node subtreeNode;
private final int lockMode;
private final int sessionId;
private EventStore eventStore;
private Vector dataPlugins;
private int state;
// Session creation is done in two phases:
// - DmtAdmin creates a new DmtSessionImpl instance (this should indicate
// as many errors as possible, but must not call any plugins)
// - when all conflicting sessions have been closed, DmtAdmin calls "open()"
// to actually open the session for external use
DmtSessionImpl(String principal, String subtreeUri, int lockMode,
PermissionInfo[] permissions, Context context,
DmtAdminCore dmtAdmin) throws DmtException {
Node node = Node.validateAndNormalizeUri(subtreeUri);
subtreeNode = node.isAbsolute() ?
node : Node.ROOT_NODE.appendRelativeNode(node);
this.principal = principal;
this.lockMode = lockMode;
this.dmtAdmin = dmtAdmin;
this.context = context;
if(principal != null) { // remote session
SecurityManager sm = System.getSecurityManager();
if(sm != null)
sm.checkPermission(new DmtPrincipalPermission(principal));
try {
securityContext = getSecurityContext(permissions);
} catch(Exception e) {
throw new DmtException(subtreeNode.getUri(),
DmtException.COMMAND_FAILED,
"Unable to create Protection Domain for remote server.",
e);
}
} else
securityContext = null;
sessionId =
(new Long(System.currentTimeMillis())).hashCode() ^ hashCode();
eventStore = new EventStore(context, sessionId);
dataPlugins = new Vector();
state = STATE_CLOSED;
}
// called directly before returning the session object in getSession()
// throws NODE_NOT_FOUND if the previously specified root does not exist
void open() throws DmtException {
if(lockMode == LOCK_TYPE_ATOMIC)
// shallow copy is enough, Nodes and Acls are immutable
savedAcls = (Hashtable) acls.clone();
state = STATE_OPEN;
// after everything is initialized, check with the plugins whether the
// given node really exists
checkNode(subtreeNode, SHOULD_EXIST);
eventStore.dispatchSessionLifecycleEvent(DmtEvent.SESSION_OPENED);
}
// called by Dmt Admin when checking session conflicts
Node getRootNode() {
return subtreeNode;
}
// called by the Session Wrapper, rollback parameter is:
// - true if a fatal exception has been thrown in a DMT access method
// - false if any exception has been thrown in the commit/rollback methods
protected void invalidateSession(boolean rollback, boolean timeout) {
state = STATE_INVALID;
context.log(LogService.LOG_WARNING, "Invalidating session '" +
sessionId + "' because of " + (timeout ? "timeout." : "error."),
null);
if(lockMode == LOCK_TYPE_ATOMIC && rollback) {
try {
rollbackPlugins();
} catch(DmtException e) {
context.log(LogService.LOG_WARNING, "Error rolling back " +
"plugin while invalidating session.", e);
}
}
try {
closeAndRelease(false);
} catch(DmtException e) {
context.log(LogService.LOG_WARNING, "Error closing plugin while " +
"invalidating session.", e);
}
}
/* These methods can be called even before the session has been opened, and
* also after the session has been closed. */
public synchronized int getState() {
return state;
}
public String getPrincipal() {
return principal;
}
public int getSessionId() {
return sessionId;
}
public String getRootUri() {
return subtreeNode.getUri();
}
public int getLockType() {
return lockMode;
}
/* These methods are only meaningful in the context of an open session. */
// no other API methods can be called while this method is executed
public synchronized void close() throws DmtException {
checkSession();
// changed to CLOSED if this method finishes without error
state = STATE_INVALID;
closeAndRelease(lockMode == LOCK_TYPE_ATOMIC);
// TODO also send session closed event whenever session is invalidated?
eventStore.dispatchSessionLifecycleEvent(DmtEvent.SESSION_CLOSED);
state = STATE_CLOSED;
}
private void closeAndRelease(boolean commit) throws DmtException {
try {
if(commit)
commitPlugins();
closePlugins();
} finally {
// DmtAdmin must be notified that this session has ended, otherwise
// other sessions might never be allowed to run
dmtAdmin.releaseSession(this);
}
}
private void closePlugins() throws DmtException {
Vector closeExceptions = new Vector();
// this block requires synchronization
ListIterator i = dataPlugins.listIterator(dataPlugins.size());
while (i.hasPrevious()) {
try {
((PluginSessionWrapper) i.previous()).close();
} catch(Exception e) {
closeExceptions.add(e);
}
}
dataPlugins.clear();
if (closeExceptions.size() != 0)
throw new DmtException((String) null, DmtException.COMMAND_FAILED,
"Some plugins failed to close.", closeExceptions, false);
}
// no other API methods can be called while this method is executed
public synchronized void commit() throws DmtException {
checkSession();
if (lockMode != LOCK_TYPE_ATOMIC)
throw new IllegalStateException("Commit can only be requested " +
"for atomic sessions.");
// changed back to OPEN if this method finishes without error
state = STATE_INVALID;
commitPlugins();
savedAcls = (Hashtable) acls.clone();
state = STATE_OPEN;
}
// precondition: lockMode == LOCK_TYPE_ATOMIC
private void commitPlugins() throws DmtException {
Vector commitExceptions = new Vector();
ListIterator i = dataPlugins.listIterator(dataPlugins.size());
// this block requires synchronization
while (i.hasPrevious()) {
PluginSessionWrapper wrappedPlugin = (PluginSessionWrapper) i.previous();
try {
// checks transaction support before calling commit on the plugin
wrappedPlugin.commit();
} catch(Exception e) {
eventStore.excludeRoot(wrappedPlugin.getSessionRoot());
commitExceptions.add(e);
}
}
eventStore.dispatchEvents();
if (commitExceptions.size() != 0)
throw new DmtException((String) null,
DmtException.TRANSACTION_ERROR,
"Some plugins failed to commit.",
commitExceptions, false);
}
// no other API methods can be called while this method is executed
public synchronized void rollback() throws DmtException {
checkSession();
if (lockMode != LOCK_TYPE_ATOMIC)
throw new IllegalStateException("Rollback can only be requested " +
"for atomic sessions.");
// changed back to OPEN if this method finishes without error
state = STATE_INVALID;
acls = (Hashtable) savedAcls.clone();
rollbackPlugins();
state = STATE_OPEN;
}
// precondition: lockMode == LOCK_TYPE_ATOMIC
private void rollbackPlugins() throws DmtException {
eventStore.clear();
Vector rollbackExceptions = new Vector();
// this block requires synchronization
ListIterator i = dataPlugins.listIterator(dataPlugins.size());
while (i.hasPrevious()) {
try {
// checks transaction support before calling rollback on the plugin
((PluginSessionWrapper) i.previous()).rollback();
} catch(Exception e) {
rollbackExceptions.add(e);
}
}
if (rollbackExceptions.size() != 0)
throw new DmtException((String) null, DmtException.ROLLBACK_FAILED,
"Some plugins failed to roll back or close.",
rollbackExceptions, false);
}
public synchronized void execute(String nodeUri, String data)
throws DmtException {
internalExecute(nodeUri, null, data);
}
public synchronized void execute(String nodeUri, String correlator,
String data) throws DmtException {
internalExecute(nodeUri, correlator, data);
}
// same as execute/3 but can be called internally, because it is not wrapped
private void internalExecute(String nodeUri, final String correlator,
final String data) throws DmtException {
checkSession();
// not allowing to execute non-existent nodes, all Management Objects
// defined in the spec have data plugins backing them
final Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.EXEC, MetaNode.CMD_EXECUTE);
final ExecPlugin plugin =
context.getPluginDispatcher().getExecPlugin(node);
final DmtSession session = this;
if (plugin == null)
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"No exec plugin registered for given node.");
try {
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws DmtException {
plugin.execute(session, node.getPath(), correlator, data);
return null;
}
}, securityContext);
} catch(PrivilegedActionException e) {
throw (DmtException) e.getException();
}
}
// requires DmtPermission with GET action, no ACL check done because there
// are no ACLs stored for non-existing nodes (in theory)
public synchronized boolean isNodeUri(String nodeUri) {
checkSession();
try {
Node node = makeAbsoluteUri(nodeUri);
checkLocalPermission(node, writeAclCommands(Acl.GET));
checkNode(node, SHOULD_EXIST);
// not checking meta-data for the GET capability, the plugin must be
// prepared to answer isNodeUri() even if the node is not "gettable"
} catch (DmtException e) {
return false; // invalid node URI or error opening plugin
}
return true;
}
public synchronized boolean isLeafNode(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return isLeafNodeNoCheck(node);
}
// GET property op
public synchronized Acl getNodeAcl(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
Acl acl = (Acl) acls.get(node);
return acl == null ? null : acl;
}
// GET property op
public synchronized Acl getEffectiveNodeAcl(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getEffectiveNodeAclNoCheck(node);
}
// REPLACE property op
public synchronized void setNodeAcl(String nodeUri, Acl acl)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
// check for REPLACE permission:
if (isLeafNodeNoCheck(node)) // on the parent node for leaf nodes
checkNodePermission(node.getParent(), Acl.REPLACE);
else // on the node itself or the parent for interior nodes (parent will
// be ignored in case of the root node)
checkNodeOrParentPermission(node, Acl.REPLACE);
// Not checking REPLACE capability, node does not have to be modifiable
// to have an ACL associated with it. It should be possible to set
// ACLs everywhere, and the "Replace" Access Type seems to be given
// only for modifiable nodes.
// check that the new ACL is valid
if(node.isRoot() && (acl == null || !acl.isPermitted("*", Acl.ADD)))
// should be 405 "Forbidden" according to DMTND 7.7.1.2
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED, "Root ACL must allow " +
"the Add operation for all principals.");
if (acl == null || isEmptyAcl(acl))
acls.remove(node);
else
acls.put(node, acl);
getReadableDataSession(node).nodeChanged(node.getPath());
enqueueEventWithCurrentAcl(DmtEvent.REPLACED, node, null);
}
public synchronized MetaNode getMetaNode(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
checkNodePermission(node, Acl.GET);
// not checking meta-data for the GET capability, meta-data should
// always be publicly available
return getMetaNodeNoCheck(node);
}
public synchronized DmtData getNodeValue(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
return internalGetNodeValue(node);
}
// also used by copy() to pass an already validated Node instead of a URI
private DmtData internalGetNodeValue(Node node) throws DmtException {
// VEG CR supporting values for interior nodes
checkNode(node, SHOULD_EXIST);
//checkNode(node, SHOULD_BE_LEAF);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
// VEG CR supporting values for interior nodes
if(!isLeafNodeNoCheck(node)) {
checkDescendantGetPermissions(node);
checkInteriorNodeValueSupport(node);
}
ReadableDataSession pluginSession = getReadableDataSession(node);
DmtData data = pluginSession.getNodeValue(node.getPath());
// VEG CR supporting values for interior nodes
boolean isLeafNode = pluginSession.isLeafNode(node.getPath());
boolean isLeafData = data.getFormat() != DmtData.FORMAT_NODE;
if(isLeafNode != isLeafData)
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"Error retrieving node value, the type of the data " +
"returned by the plugin does not match the node type.");
return data;
}
// VEG CR supporting values for interior nodes
private void checkDescendantGetPermissions(Node node) throws DmtException {
checkNodePermission(node, Acl.GET);
if (!isLeafNodeNoCheck(node)) {
String[] children = internalGetChildNodeNames(node);
// 'children' is [] if there are no child nodes
for (int i = 0; i < children.length; i++)
checkDescendantGetPermissions(node.appendSegment(children[i]));
}
}
public synchronized String[] getChildNodeNames(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
return internalGetChildNodeNames(node);
}
// also used by copy() to pass an already validated Node instead of a URI
private String[] internalGetChildNodeNames(Node node) throws DmtException {
checkNode(node, SHOULD_BE_INTERIOR);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
String[] pluginChildNodes =
getReadableDataSession(node).getChildNodeNames(node.getPath());
List processedChildNodes = normalizeChildNodeNames(pluginChildNodes);
String[] processedChildNodeArray = (String[])
processedChildNodes.toArray(new String[processedChildNodes.size()]);
// ordering is not a requirement, but allows easier testing of plugins
Arrays.sort(processedChildNodeArray);
return processedChildNodeArray;
}
// GET property op
public synchronized String getNodeTitle(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
return internalGetNodeTitle(node);
}
// also used by copy() to pass an already validated Node instead of a URI
private String internalGetNodeTitle(Node node) throws DmtException {
checkNode(node, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeTitle(node.getPath());
}
// GET property op
public synchronized int getNodeVersion(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeVersion(node.getPath());
}
// GET property op
public synchronized Date getNodeTimestamp(String nodeUri)
throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeTimestamp(node.getPath());
}
// GET property op
public synchronized int getNodeSize(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_BE_LEAF);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeSize(node.getPath());
}
// GET property op
public synchronized String getNodeType(String nodeUri) throws DmtException {
checkSession();
Node node = makeAbsoluteUri(nodeUri);
return internalGetNodeType(node);
}
// also used by copy() to pass an already validated Node instead of a URI
private String internalGetNodeType(Node node) throws DmtException {
checkNode(node, SHOULD_EXIST);
checkOperation(node, Acl.GET, MetaNode.CMD_GET);
return getReadableDataSession(node).getNodeType(node.getPath());
}
// REPLACE property op
public synchronized void setNodeTitle(String nodeUri, String title)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
internalSetNodeTitle(node, title, true); // send event if successful
}
// also used by copy() to pass an already validated Node instead of a URI
// and to set the node title without triggering an event
private void internalSetNodeTitle(Node node, String title,
boolean sendEvent) throws DmtException {
checkNode(node, SHOULD_EXIST);
checkOperation(node, Acl.REPLACE, MetaNode.CMD_REPLACE);
try {
if (title != null && title.getBytes("UTF-8").length > 255)
throw new DmtException(node.getUri(),
DmtException.COMMAND_FAILED,
"Length of Title property exceeds 255 bytes (UTF-8).");
} catch (UnsupportedEncodingException e) {
// never happens
}
getReadWriteDataSession(node).setNodeTitle(node.getPath(), title);
if(sendEvent)
enqueueEventWithCurrentAcl(DmtEvent.REPLACED, node, null);
}
public synchronized void setNodeValue(String nodeUri, DmtData data)
throws DmtException {
commonSetNodeValue(nodeUri, data);
}
public synchronized void setDefaultNodeValue(String nodeUri)
throws DmtException {
commonSetNodeValue(nodeUri, null);
}
private void commonSetNodeValue(String nodeUri, DmtData data)
throws DmtException {
checkWriteSession();
// VEG CR supporting values for interior nodes
int nodeConstraint =
data == null ? SHOULD_EXIST :
data.getFormat() == DmtData.FORMAT_NODE ?
SHOULD_BE_INTERIOR : SHOULD_BE_LEAF;
//int nodeConstraint = SHOULD_BE_LEAF;
Node node = makeAbsoluteUriAndCheck(nodeUri, nodeConstraint);
checkOperation(node, Acl.REPLACE, MetaNode.CMD_REPLACE);
// VEG CR supporting values for interior nodes
// check data against meta-data in case of leaf nodes (meta-data does
// not contain constraints for interior node values)
if(isLeafNodeNoCheck(node))
checkValue(node, data);
else
checkInteriorNodeValueSupport(node);
//checkValue(node, data);
MetaNode metaNode = getMetaNodeNoCheck(node);
if (metaNode != null && metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(), DmtException.METADATA_MISMATCH,
"Cannot set the value of a permanent node.");
getReadWriteDataSession(node).setNodeValue(node.getPath(), data);
// VEG CR supporting values for interior nodes
traverseEvents(DmtEvent.REPLACED, node);
//enqueueEvent(DmtEvent.REPLACED, node);
}
// VEG CR supporting values for interior nodes
private void traverseEvents(int mode, Node node) throws DmtException {
if(isLeafNodeNoCheck(node))
enqueueEventWithCurrentAcl(mode, node, null);
else {
String children[] = internalGetChildNodeNames(node);
Arrays.sort(children);
for (int i = 0; i < children.length; i++)
traverseEvents(mode, node.appendSegment(children[i]));
}
}
// SyncML DMTND 7.5 (p16) Type: only the Get command is applicable!
public synchronized void setNodeType(String nodeUri, String type)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.REPLACE, MetaNode.CMD_REPLACE);
MetaNode metaNode = getMetaNodeNoCheck(node);
if (metaNode != null && metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(), DmtException.METADATA_MISMATCH,
"Cannot set type property of permanent node.");
if(isLeafNodeNoCheck(node))
checkMimeType(node, type);
// could check type string for interior nodes, but this impl. does not
// handle it anyway, so we leave it to the plugins if they need it
// (same in createInteriorNode/2)
getReadWriteDataSession(node).setNodeType(node.getPath(), type);
enqueueEventWithCurrentAcl(DmtEvent.REPLACED, node, null);
}
public synchronized void deleteNode(String nodeUri) throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
if(node.isRoot())
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"Cannot delete root node.");
checkOperation(node, Acl.DELETE, MetaNode.CMD_DELETE);
MetaNode metaNode = getMetaNodeNoCheck(node);
if (metaNode != null) {
if(metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot delete permanent node.");
if(!metaNode.isZeroOccurrenceAllowed()) {
// maxOccurrence == 1 means that there cannot be other instances
// of this node, so it cannot be deleted. If maxOccurrence > 1
// then we have to check whether this is the last one.
if(metaNode.getMaxOccurrence() == 1)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Metadata does not allow deleting the only " +
"instance of this node.");
checkNodeIsInSession(node.getParent(), "(needed to determine" +
"the number of siblings of the given node) ");
if(getNodeCardinality(node) == 1)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Metadata does not allow deleting the last " +
"instance of this node.");
}
}
getReadWriteDataSession(node).deleteNode(node.getPath());
Acl acl = getEffectiveNodeAclNoCheck(node);
moveAclEntries(node, null);
enqueueEvent(DmtEvent.DELETED, node, null, acl);
}
public synchronized void createInteriorNode(String nodeUri)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateInteriorNode(node, null, true, false);
}
public synchronized void createInteriorNode(String nodeUri, String type)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateInteriorNode(node, type, true, false);
}
// - used by the other createInteriorNode variants
// - also used by copy() to pass an already validated Node instead of a URI
// and to create interior nodes without triggering an event
// - also used by ensureInteriorAncestors, to create missing nodes while
// skipping automatically created nodes
private void commonCreateInteriorNode(Node node, String type,
boolean sendEvent, boolean skipAutomatic) throws DmtException {
checkNode(node, SHOULD_NOT_EXIST);
Node parent = node.getParent();
if(parent == null) // this should never happen, root must always exist
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"Cannot create root node.");
// Return silently if all of the following conditions are met:
// - the parent node has been created while ensuring that the ancestor
// nodes all exist
// - this call is part of creating the ancestors for some sub-node (as
// indicated by 'skipAutomatic')
// - this current node was created automatically, triggered by the
// creation of the parent (i.e. it has AUTOMATIC scope)
if(ensureInteriorAncestors(parent, sendEvent) && skipAutomatic &&
getReadableDataSession(node).isNodeUri(node.getPath()))
return;
checkNodePermission(parent, Acl.ADD);
checkNodeCapability(node, MetaNode.CMD_ADD);
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode != null && metaNode.isLeaf())
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot create the specified interior node, " +
"meta-data defines it as a leaf node.");
// could check type string, but this impl. does not handle it anyway
// so we leave it to the plugins if they need it (same in setNodeType)
checkNewNode(node);
checkMaxOccurrence(node);
// it is not really useful to allow creating automatic nodes, but this
// is not a hard requirement, and should be enforced by the (lack of
// the) ADD access type instead
getReadWriteDataSession(node).createInteriorNode(node.getPath(), type);
assignNewNodePermissions(node, parent);
if(sendEvent)
enqueueEventWithCurrentAcl(DmtEvent.ADDED, node, null);
}
public synchronized void createLeafNode(String nodeUri) throws DmtException {
// not calling createLeafNode/3, because it is wrapped
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateLeafNode(node, null, null, true);
}
public synchronized void createLeafNode(String nodeUri, DmtData value)
throws DmtException {
// not calling createLeafNode/3, because it is wrapped
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateLeafNode(node, value, null, true);
}
public synchronized void createLeafNode(String nodeUri, DmtData value,
String mimeType) throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUri(nodeUri);
commonCreateLeafNode(node, value, mimeType, true);
}
// - used by the other createLeafNode variants
// - also used by copy() to pass an already validated Node instead of a URI
// and to create leaf nodes without triggering an event
private void commonCreateLeafNode(Node node, DmtData value,
String mimeType, boolean sendEvent) throws DmtException {
checkNode(node, SHOULD_NOT_EXIST);
Node parent = node.getParent();
if(parent == null) // this should never happen, root must always exist
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"Cannot create root node.");
ensureInteriorAncestors(parent, sendEvent);
checkNodePermission(parent, Acl.ADD);
checkNodeCapability(node, MetaNode.CMD_ADD);
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode != null && !metaNode.isLeaf())
throw new DmtException(node.getUri(), DmtException.METADATA_MISMATCH,
"Cannot create the specified leaf node, meta-data " +
"defines it as an interior node.");
checkNewNode(node);
checkValue(node, value);
checkMimeType(node, mimeType);
checkMaxOccurrence(node);
// it is not really useful to allow creating automatic nodes, but this
// is not a hard requirement, and should be enforced by the (lack of
// the) ADD access type instead
getReadWriteDataSession(node).createLeafNode(node.getPath(), value,
mimeType);
if(sendEvent)
enqueueEventWithCurrentAcl(DmtEvent.ADDED, node, null);
}
// Tree may be left in an inconsistent state if there is an error when only
// part of the tree has been copied.
public synchronized void copy(String nodeUri, String newNodeUri,
boolean recursive) throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
Node newNode = makeAbsoluteUriAndCheck(newNodeUri, SHOULD_NOT_EXIST);
if (node.isAncestorOf(newNode))
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"Cannot copy node to its descendant, '" + newNode + "'.");
if (context.getPluginDispatcher()
.handledBySameDataPlugin(node, newNode)) {
Node newParentNode = newNode.getParent();
// newParentNode cannot be null, because newNode is a valid absolute
// nonexisting node, so it cannot be the root
ensureInteriorAncestors(newParentNode, false);
// DMTND 7.7.1.5: "needs correct access rights for the equivalent
// Add, Delete, Get, and Replace commands"
copyPermissionCheck(node, newParentNode, newNode, recursive);
checkNodeCapability(node, MetaNode.CMD_GET);
checkNodeCapability(newNode, MetaNode.CMD_ADD);
checkNewNode(newNode);
checkMaxOccurrence(newNode);
// for leaf nodes: since we are not passing a data object to the
// plugin, checking the value and mime-type against the new
// meta-data is the responsibility of the plugin itself
try {
getReadWriteDataSession(newNode).copy(node.getPath(),
newNode.getPath(), recursive);
assignNewNodePermissions(newNode, newParentNode);
} catch(DmtException e) {
// fall back to generic algorithm if plugin doesn't support copy
if(e.getCode() != DmtException.FEATURE_NOT_SUPPORTED)
throw e;
// the above checks will be performed again, but we cannot even
// attempt to call the plugin without them
copyNoCheck(node, newNode, recursive);
}
}
else
copyNoCheck(node, newNode, recursive); // does not trigger events
Acl acl = getEffectiveNodeAclNoCheck(node);
Acl newAcl = getEffectiveNodeAclNoCheck(newNode);
Acl mergedAcl = mergeAcls(acl, newAcl);
enqueueEvent(DmtEvent.COPIED, node, newNode, mergedAcl);
}
public synchronized void renameNode(String nodeUri, String newNodeName)
throws DmtException {
checkWriteSession();
Node node = makeAbsoluteUriAndCheck(nodeUri, SHOULD_EXIST);
checkOperation(node, Acl.REPLACE, MetaNode.CMD_REPLACE);
Node parent = node.getParent();
if (parent == null)
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"Cannot rename root node.");
String newName = Node.validateAndNormalizeNodeName(newNodeName);
Node newNode = parent.appendSegment(newName);
checkNode(newNode, SHOULD_NOT_EXIST);
checkNewNode(newNode);
MetaNode metaNode = getMetaNodeNoCheck(node);
MetaNode newMetaNode = getMetaNodeNoCheck(newNode);
if (metaNode != null) {
if(metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot rename permanent node.");
int maxOcc = metaNode.getMaxOccurrence();
// sanity check: all siblings of a node must either have a
// cardinality of 1, or they must be part of the same multi-node
if(newMetaNode != null && maxOcc != newMetaNode.getMaxOccurrence())
throw new DmtException(node.getUri(),
DmtException.COMMAND_FAILED,
"Cannot rename node, illegal meta-data found (a " +
"member of a multi-node has a sibling with different " +
"meta-data).");
// if this is a multi-node (maxOcc > 1), renaming does not affect
// the cardinality
if(maxOcc == 1 && !metaNode.isZeroOccurrenceAllowed())
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Metadata does not allow deleting last instance of " +
"this node.");
}
// the new node must be the same (leaf/interior) as the original
if(newMetaNode != null && newMetaNode.isLeaf() != isLeafNodeNoCheck(node))
throw new DmtException(newNode.getUri(),
DmtException.METADATA_MISMATCH,
"The destination of the rename operation is " +
(newMetaNode.isLeaf() ? "a leaf" : "an interior") +
" node according to the meta-data, which does not match " +
"the source node.");
// for leaf nodes: since we are not passing a data object to the
// plugin, checking the value and mime-type against the new
// meta-data is the responsibility of the plugin itself
getReadWriteDataSession(node).renameNode(node.getPath(), newName);
Acl acl = getEffectiveNodeAclNoCheck(node);
moveAclEntries(node, newNode);
enqueueEvent(DmtEvent.RENAMED, node, newNode, acl);
}
/**
* Create an Access Control Context based on the given permissions. The
* Permission objects are first created from the PermissionInfo objects,
* then added to a permission collection, which is added to a protection
* domain with no code source, which is used to create the access control
* context. If the <code>null</code> argument is given, an empty access
* control context is created.
*
* @throws Exception if there is an error creating one of the permission
* objects (can be one of ClassNotFoundException, SecurityException,
* NoSuchMethodException, ClassCastException,
* IllegalArgumentException, InstantiationException,
* IllegalAccessException or InvocationTargetException)
*/
private AccessControlContext getSecurityContext(PermissionInfo[] permissions)
throws Exception {
PermissionCollection permissionCollection = new Permissions();
if(permissions != null)
for (int i = 0; i < permissions.length; i++) {
PermissionInfo info = permissions[i];
Class permissionClass = Class.forName(info.getType());
Constructor constructor = permissionClass
.getConstructor(PERMISSION_CONSTRUCTOR_SIG);
Permission permission = (Permission) constructor.newInstance(
new Object[] {info.getName(), info.getActions()});
permissionCollection.add(permission);
}
return new AccessControlContext(new ProtectionDomain[] {
new ProtectionDomain(null, permissionCollection)});
}
private void checkSession() {
if(state != STATE_OPEN)
throw new IllegalStateException(
"Session is not open, cannot perform DMT operations.");
}
private void checkWriteSession() {
checkSession();
if(lockMode == LOCK_TYPE_SHARED)
throw new IllegalStateException(
"Session is not open for writing, cannot perform " +
"requested write operation.");
}
private Acl mergeAcls(Acl acl1, Acl acl2) {
Acl mergedAcl = acl1;
String[] principals = acl2.getPrincipals();
for (int i = 0; i < principals.length; i++)
mergedAcl = mergedAcl.addPermission(principals[i], acl2
.getPermissions(principals[i]));
mergedAcl.addPermission("*", acl2.getPermissions("*"));
return mergedAcl;
}
private void enqueueEventWithCurrentAcl(int type, Node node, Node newNode) {
Acl acl = null;
if(node != null)
acl = getEffectiveNodeAclNoCheck(node);
enqueueEvent(type, node, newNode, acl);
}
private void enqueueEvent(int type, Node node, Node newNode, Acl acl) {
boolean isAtomic = lockMode == LOCK_TYPE_ATOMIC;
eventStore.add(type, node, newNode, acl, isAtomic);
}
private boolean isLeafNodeNoCheck(Node node) throws DmtException {
return getReadableDataSession(node).isLeafNode(node.getPath());
}
private MetaNode getMetaNodeNoCheck(Node node) throws DmtException {
return getReadableDataSession(node).getMetaNode(node.getPath());
}
// precondition: 'uri' must point be valid (checked with isNodeUri or
// returned by getChildNodeNames)
private void copyNoCheck(Node node, Node newNode, boolean recursive)
throws DmtException {
boolean isLeaf = isLeafNodeNoCheck(node);
String type = internalGetNodeType(node);
// create new node (without sending a separate event about it)
if (isLeaf)
// if getNodeValue() returns null, we attempt to set the default
commonCreateLeafNode(newNode, internalGetNodeValue(node), type,
false);
else
commonCreateInteriorNode(newNode, type, false, false);
// copy Title property (without sending event) if it is supported by
// both source and target plugins
try {
String title = internalGetNodeTitle(node);
// It could be valid to copy "null" Titles as well, if the
// implementation has default values for the Title property.
if(title != null)
internalSetNodeTitle(newNode, title, false);
} catch (DmtException e) {
if (e.getCode() != DmtException.FEATURE_NOT_SUPPORTED)
throw new DmtException(node.getUri(),
DmtException.COMMAND_FAILED, "Error copying node to '" +
newNode + "', cannot copy title.", e);
}
// Format, Name, Size, TStamp and VerNo properties do not need to be
// expicitly copied
// copy children if mode is recursive and node is interior
if (recursive && !isLeaf) {
// 'children' is [] if there are no child nodes
String[] children = internalGetChildNodeNames(node);
for (int i = 0; i < children.length; i++)
copyNoCheck(node.appendSegment(children[i]),
newNode.appendSegment(children[i]), true);
}
}
// precondition: path must be absolute, and the parent of the given node
// must be within the subtree of the session
private int getNodeCardinality(Node node) throws DmtException {
Node parent = node.getParent();
String[] neighbours =
getReadableDataSession(parent).getChildNodeNames(parent.getPath());
return normalizeChildNodeNames(neighbours).size();
}
private void assignNewNodePermissions(Node node, Node parent)
throws DmtException {
// DMTND 7.7.1.3: if parent does not have Replace permissions, give Add,
// Delete and Replace permissions to child. (This rule cannot be
// applied to Java permissions, only to ACLs.)
if(principal != null) {
try {
checkNodePermission(parent, Acl.REPLACE);
} catch (DmtException e) {
if (e.getCode() != DmtException.PERMISSION_DENIED)
throw e; // should not happen
Acl parentAcl = getEffectiveNodeAclNoCheck(parent);
Acl newAcl = parentAcl.addPermission(principal, Acl.ADD
| Acl.DELETE | Acl.REPLACE);
acls.put(node, newAcl);
}
}
}
private void checkOperation(Node node, int actions, int capability)
throws DmtException {
checkNodePermission(node, actions);
checkNodeCapability(node, capability);
}
// throws SecurityException if principal is local user, and sufficient
// privileges are missing
private void checkNodePermission(Node node, int actions)
throws DmtException {
checkNodeOrParentPermission(principal, node, actions, false);
}
// throws SecurityException if principal is local user, and sufficient
// privileges are missing
private void checkNodeOrParentPermission(Node node, int actions)
throws DmtException {
checkNodeOrParentPermission(principal, node, actions, true);
}
// Performs the necessary permission checks for a copy operation:
// - checks that the caller has GET rights (ACL or Java permission) for all
// source nodes
// - in case of local sessions, checks that the caller has REPLACE Java
// permissions on all nodes where a title needs to be set, and ADD Java
// permissions for the parents of all added nodes
// - in case of remote sessions, only the ACL of the parent of the target
// node needs to be checked, because ACLs cannot be set for nonexitent
// nodes; in this case the ADD ACL is always required, while REPLACE is
// checked only if any of the copied nodes has a non-null Title string
//
// Precondition: 'node' must point be valid (checked with isNodeUri or
// returned by getChildNodeNames)
private void copyPermissionCheck(Node node, Node newParentNode,
Node newNode, boolean recursive) throws DmtException {
boolean hasTitle = copyPermissionCheckRecursive(node, newParentNode,
newNode, recursive);
// ACL not copied, so the parent of the target node only needs
// REPLACE permission if the copied node (or any node in the copied
// subtree) has a title
// remote access permissions for the target only need to be checked once
if(principal != null) {
checkNodePermission(newParentNode, Acl.ADD);
if(hasTitle)
checkNodePermission(newNode, Acl.REPLACE);
}
}
private boolean copyPermissionCheckRecursive(Node node,
Node newParentNode, Node newNode, boolean recursive)
throws DmtException {
// check that the caller has GET rights for the current node
checkNodePermission(node, Acl.GET);
// check whether the node has a non-null title
boolean hasTitle = nodeHasTitle(node);
// local access permissions need to be checked for each target node
if(principal == null) {
checkLocalPermission(newParentNode, writeAclCommands(Acl.ADD));
if(hasTitle)
checkLocalPermission(newNode, writeAclCommands(Acl.REPLACE));
}
// perform the checks recursively for the subtree if requested
if (recursive && !isLeafNodeNoCheck(node)) {
// 'children' is [] if there are no child nodes
String[] children = internalGetChildNodeNames(node);
for (int i = 0; i < children.length; i++)
if(copyPermissionCheckRecursive(node.appendSegment(children[i]),
newNode, newNode.appendSegment(children[i]), true))
hasTitle = true;
}
return hasTitle;
}
// Returns true if the plugin handling the given node supports the Title
// property and value of the property is non-null. This is used for
// determining whether the caller needs to have REPLACE rights for the
// target node of the enclosing copy operation.
private boolean nodeHasTitle(Node node) throws DmtException {
try {
return internalGetNodeTitle(node) != null;
} catch (DmtException e) {
// FEATURE_NOT_SUPPORTED means that Title is not supported
if (e.getCode() != DmtException.FEATURE_NOT_SUPPORTED)
throw e;
}
return false;
}
private Node makeAbsoluteUriAndCheck(String nodeUri, int check)
throws DmtException {
Node node = makeAbsoluteUri(nodeUri);
checkNode(node, check);
return node;
}
// returns a plugin for read-only use
private ReadableDataSession getReadableDataSession(Node node)
throws DmtException {
return getPluginSession(node, false);
}
// returns a plugin for writing
private ReadWriteDataSession getReadWriteDataSession(Node node)
throws DmtException {
return getPluginSession(node, true);
}
// precondition: if 'writable' is true, session lock type must not be shared
// 'synchronized' is just indication, all entry points are synch'd anyway
private synchronized PluginSessionWrapper getPluginSession(Node node,
boolean writeOperation) throws DmtException {
PluginSessionWrapper wrappedPlugin = null;
Node wrappedPluginRoot = null;
// Look through the open plugin sessions, and find the session with the
// lowest root that handles the given node.
Iterator i = dataPlugins.iterator();
while (i.hasNext()) {
PluginSessionWrapper plugin = (PluginSessionWrapper) i.next();
Node pluginRoot = plugin.getSessionRoot();
if(pluginRoot.isAncestorOf(node) && (wrappedPluginRoot == null ||
wrappedPluginRoot.isAncestorOf(pluginRoot))) {
wrappedPlugin = plugin;
wrappedPluginRoot = pluginRoot;
}
}
// Find the plugin that would/will handle the given node, and the root
// of the (potential) session opened on it.
PluginRegistration pluginRegistration =
context.getPluginDispatcher().getDataPlugin(node);
Node root = getRootForPlugin(pluginRegistration, node);
// If we found a plugin session handling the node, and the potential
// new plugin session root (defined by 'root') is not in its subtree,
// then use the open session. If there is no session yet, or if a new
// session could be opened with a deeper root, then a new session is
// opened. (This guarantees that the proper plugin is used instead of
// the root plugin for nodes below the "root tree".)
if(wrappedPlugin != null &&
!wrappedPluginRoot.isAncestorOf(root, true)) {
if(writeOperation &&
wrappedPlugin.getSessionType() == LOCK_TYPE_SHARED)
throw getWriteException(lockMode, node);
return wrappedPlugin;
}
// No previously opened session found, attempting to open session with
// correct lock type.
DataPlugin plugin = pluginRegistration.getDataPlugin();
ReadableDataSession pluginSession = null;
int pluginSessionType = lockMode;
if(lockMode != LOCK_TYPE_SHARED) {
pluginSession = openPluginSession(plugin, root, pluginSessionType);
if(pluginSession == null && writeOperation)
throw getWriteException(lockMode, node);
}
// read-only session if lockMode is LOCK_TYPE_SHARED, or if the
// plugin did not support the writing lock mode, and the current
// operation is for reading
if(pluginSession == null) {
pluginSessionType = LOCK_TYPE_SHARED;
pluginSession = openPluginSession(plugin, root, pluginSessionType);
}
wrappedPlugin = new PluginSessionWrapper(pluginRegistration,
pluginSession, pluginSessionType, root, securityContext);
// this requires synchronized access
dataPlugins.add(wrappedPlugin);
return wrappedPlugin;
}
private Node getRootForPlugin(PluginRegistration plugin, Node node) {
Node[] roots = plugin.getDataRoots();
for(int i = 0; i < roots.length; i++)
if(roots[i].isAncestorOf(node))
return roots[i].isAncestorOf(subtreeNode)
? subtreeNode : roots[i];
throw new IllegalStateException("Internal error, plugin root not " +
"found for a URI handled by the plugin.");
}
private ReadableDataSession openPluginSession(
final DataPlugin plugin, Node root,
final int pluginSessionType) throws DmtException {
final DmtSession session = this;
final String[] rootPath = root.getPath();
ReadableDataSession pluginSession;
try {
pluginSession = (ReadableDataSession)
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws DmtException {
switch(pluginSessionType) {
case LOCK_TYPE_EXCLUSIVE:
return plugin.openReadWriteSession(rootPath, session);
case LOCK_TYPE_ATOMIC:
return plugin.openAtomicSession(rootPath, session);
default: // LOCK_TYPE_SHARED
return plugin.openReadOnlySession(rootPath, session);
}
}
}, securityContext);
} catch(PrivilegedActionException e) {
throw (DmtException) e.getException();
}
return pluginSession;
}
// precondition: path must be absolute
private void checkNode(Node node, int check) throws DmtException {
boolean shouldExist = (check != SHOULD_NOT_EXIST);
if (getReadableDataSession(node).isNodeUri(node.getPath()) != shouldExist)
throw new DmtException(node.getUri(),
shouldExist ? DmtException.NODE_NOT_FOUND
: DmtException.NODE_ALREADY_EXISTS,
"The specified URI should point to "
+ (shouldExist ? "an existing" : "a non-existent")
+ " node to perform the requested operation.");
boolean shouldBeLeaf = (check == SHOULD_BE_LEAF);
boolean shouldBeInterior = (check == SHOULD_BE_INTERIOR);
if ((shouldBeLeaf || shouldBeInterior)
&& isLeafNodeNoCheck(node) != shouldBeLeaf)
throw new DmtException(node.getUri(),
DmtException.COMMAND_NOT_ALLOWED,
"The specified URI should point to "
+ (shouldBeLeaf ? "a leaf" : "an internal")
+ " node to perform the requested operation.");
}
// precondition: checkNode() must have been called for the given uri
private void checkNodeCapability(Node node, int capability)
throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode != null && !metaNode.can(capability))
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Node meta-data does not allow the " +
capabilityName(capability) + " operation for this node.");
// default for all capabilities is 'true', if no meta-data is provided
}
private void checkValue(Node node, DmtData data) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
// if default data was requested, only check that there is a default
if(data == null) {
if(metaNode.getDefault() == null)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"This node has no default value in the meta-data.");
return;
}
if(!metaNode.isValidValue(data))
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"The specified node value is not valid according to " +
"the meta-data.");
// not checking value meta-data constraints individually, but leaving
// this to the isValidValue method of the meta-node
/*
if((metaNode.getFormat() & data.getFormat()) == 0)
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"The format of the specified value is not in the list of " +
"valid formats given in the node meta-data.");
if(data.getFormat() == DmtData.FORMAT_INTEGER) {
if(metaNode.getMax() < data.getInt())
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"Attempting to set too large integer, meta-data " +
"specifies the maximum value of " + metaNode.getMax());
if(metaNode.getMin() > data.getInt())
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"Attempting to set too small integer, meta-data " +
"specifies the minimum value of " + metaNode.getMin());
}
DmtData[] validValues = metaNode.getValidValues();
if(validValues != null && !Arrays.asList(validValues).contains(data))
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"Specified value is not in the list of valid values " +
"given in the node meta-data.");
*/
}
// precondition: path must be absolute and must specify an interior node
private void checkInteriorNodeValueSupport(Node node) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
boolean interiorNodeValueSupported = true;
try {
interiorNodeValueSupported = ((Boolean) metaNode
.getExtensionProperty(INTERIOR_NODE_VALUE_SUPPORT_PROPERTY))
.booleanValue();
} catch(IllegalArgumentException e) {
} catch(ClassCastException e) {
}
if(!interiorNodeValueSupported)
throw new DmtException(node.getUri(),
DmtException.FEATURE_NOT_SUPPORTED, "The given interior " +
"node does not support complex java values.");
}
private void checkNewNode(Node node) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
if(metaNode.getScope() == MetaNode.PERMANENT)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot create permanent node.");
if(!metaNode.isValidName(node.getLastSegment()))
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"The specified node name is not valid according to " +
"the meta-data.");
// not checking valid name list from meta-data, but leaving this to the
// isValidName method of the meta-node
/*
String[] validNames = metaNode.getValidNames();
if(validNames != null && !Arrays.asList(validNames).contains(name))
throw new DmtException(uri, DmtException.METADATA_MISMATCH,
"The specified node name is not in the list of valid " +
"names specified in the node meta-data.");
*/
}
private void checkMimeType(Node node, String type) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
if(type == null) // default MIME type was requested
return;
int sep = type.indexOf('/');
if(sep == -1 || sep == 0 || sep == type.length()-1)
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"The given type string does not contain a MIME type.");
String[] validMimeTypes = metaNode.getMimeTypes();
if(validMimeTypes != null && !Arrays.asList(validMimeTypes).contains(type))
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"The specified MIME type is not in the list of valid " +
"types in the node meta-data.");
}
private void checkMaxOccurrence(Node node) throws DmtException {
MetaNode metaNode = getMetaNodeNoCheck(node);
if(metaNode == null)
return;
// If maxOccurrence == 1 then it is not a multi-node, so it can be
// created if it did not exist before. If maxOccurrence > 1, it can
// only be created if the number of existing nodes does not reach it.
int maxOccurrence = metaNode.getMaxOccurrence();
if(maxOccurrence != Integer.MAX_VALUE && maxOccurrence > 1
&& getNodeCardinality(node) >= maxOccurrence)
throw new DmtException(node.getUri(),
DmtException.METADATA_MISMATCH,
"Cannot create the specified node, meta-data maximizes " +
"the number of instances of this node to " + maxOccurrence + ".");
}
private Node makeAbsoluteUri(String nodeUri) throws DmtException {
Node node = Node.validateAndNormalizeUri(nodeUri);
if (node.isAbsolute()) {
checkNodeIsInSession(node, "");
return node;
}
return subtreeNode.appendRelativeNode(node);
}
private void checkNodeIsInSession(Node node, String uriExplanation)
throws DmtException {
if (!subtreeNode.isAncestorOf(node))
throw new DmtException(node.getUri(), DmtException.COMMAND_FAILED,
"Specified URI " + uriExplanation + "points outside the " +
"subtree of this session.");
}
private boolean ensureInteriorAncestors(Node node, boolean sendEvent)
throws DmtException {
checkNodeIsInSession(node, "(needed to ensure " +
"a proper creation point for the new node) ");
if (!getReadableDataSession(node).isNodeUri(node.getPath())) {
commonCreateInteriorNode(node, null, sendEvent, true);
return true;
}
checkNode(node, SHOULD_BE_INTERIOR);
return false;
}
private static DmtException getWriteException(int lockMode, Node node) {
boolean atomic = (lockMode == LOCK_TYPE_ATOMIC);
return new DmtException(node.getUri(),
atomic ? DmtException.TRANSACTION_ERROR : DmtException.COMMAND_NOT_ALLOWED,
"The plugin handling the requested node does not support " +
(atomic ? "" : "non-") + "atomic writing.");
}
// remove null entries from the returned array (if it is non-null)
private static List normalizeChildNodeNames(String[] pluginChildNodes) {
List processedChildNodes = new Vector();
if (pluginChildNodes != null)
for (int i = 0; i < pluginChildNodes.length; i++)
if (pluginChildNodes[i] != null)
processedChildNodes.add(pluginChildNodes[i]);
return processedChildNodes;
}
// Move ACL entries from 'node' to 'newNode'.
// If 'newNode' is 'null', the ACL entries are removed (moved to nowhere).
private static void moveAclEntries(Node node, Node newNode) {
synchronized (acls) {
Hashtable newEntries = null;
if (newNode != null)
newEntries = new Hashtable();
Iterator i = acls.entrySet().iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
Node relativeNode =
node.getRelativeNode((Node) entry.getKey());
if (relativeNode != null) {
if (newNode != null)
newEntries.put(newNode.appendRelativeNode(relativeNode),
entry.getValue());
i.remove();
}
}
if (newNode != null)
acls.putAll(newEntries);
}
}
private static Acl getEffectiveNodeAclNoCheck(Node node) {
Acl acl;
synchronized (acls) {
acl = (Acl) acls.get(node);
// must finish whithout NullPointerException, because root ACL must
// not be empty
while (acl == null || isEmptyAcl(acl)) {
node = node.getParent();
acl = (Acl) acls.get(node);
}
}
return acl;
}
// precondition: node parameter must be an absolute node
// throws SecurityException if principal is local user, and sufficient
// privileges are missing
private static void checkNodeOrParentPermission(String name, Node node,
int actions, boolean checkParent) throws DmtException {
if(node.isRoot())
checkParent = false;
Node parent = null;
if(checkParent) // not null, as the uri is absolute but not "."
parent = node.getParent();
if (name != null) {
// succeed if the principal has the required permissions on the
// given uri, OR if the checkParent parameter is true and the
// principal has the required permissions for the parent uri
if (!(
hasAclPermission(node, name, actions) ||
checkParent && hasAclPermission(parent, name, actions)))
throw new DmtException(node.getUri(),
DmtException.PERMISSION_DENIED, "Principal '" + name
+ "' does not have the required permissions ("
+ writeAclCommands(actions) + ") on the node "
+ (checkParent ? "or its parent " : "")
+ "to perform this operation.");
}
else { // not doing local permission check if ACL check was done
String actionString = writeAclCommands(actions);
checkLocalPermission(node, actionString);
if(checkParent)
checkLocalPermission(parent, actionString);
}
}
private static boolean hasAclPermission(Node node, String name, int actions) {
return getEffectiveNodeAclNoCheck(node).isPermitted(name, actions);
}
private static void checkLocalPermission(Node node, String actions) {
SecurityManager sm = System.getSecurityManager();
if(sm != null)
sm.checkPermission(new DmtPermission(node.getUri(), actions));
}
private static String capabilityName(int capability) {
switch(capability) {
case MetaNode.CMD_ADD: return "Add";
case MetaNode.CMD_DELETE: return "Delete";
case MetaNode.CMD_EXECUTE: return "Execute";
case MetaNode.CMD_GET: return "Get";
case MetaNode.CMD_REPLACE: return "Replace";
}
// never reached
throw new IllegalArgumentException(
"Unknown meta-data capability constant " + capability + ".");
}
private static String writeAclCommands(int actions) {
String cmds = null;
cmds = writeCommand(cmds, actions, Acl.ADD, DmtPermission.ADD);
cmds = writeCommand(cmds, actions, Acl.DELETE, DmtPermission.DELETE);
cmds = writeCommand(cmds, actions, Acl.EXEC, DmtPermission.EXEC);
cmds = writeCommand(cmds, actions, Acl.GET, DmtPermission.GET);
cmds = writeCommand(cmds, actions, Acl.REPLACE, DmtPermission.REPLACE);
return (cmds != null) ? cmds : "";
}
private static String writeCommand(String base, int actions, int action,
String entry) {
if ((actions & action) != 0)
return (base != null) ? base + ',' + entry : entry;
return base;
}
private static boolean isEmptyAcl(Acl acl) {
return acl.getPermissions("*") == 0 && acl.getPrincipals().length == 0;
}
static void init_acls() {
acls = new Hashtable();
acls.put(Node.ROOT_NODE, new Acl("Add=*&Get=*&Replace=*"));
}
public String toString() {
StringBuffer info = new StringBuffer();
info.append("DmtSessionImpl(");
info.append(principal).append(", ");
info.append(subtreeNode).append(", ");
if(lockMode == LOCK_TYPE_ATOMIC)
info.append("atomic");
else if(lockMode == LOCK_TYPE_EXCLUSIVE)
info.append("exclusive");
else
info.append("shared");
info.append(", ");
if(state == STATE_CLOSED)
info.append("closed");
else if(state == STATE_OPEN)
info.append("open");
else
info.append("invalid");
return info.append(')').toString();
}
}
// Multi-purpose event store class:
// - stores sets of node URIs for the different types of changes within an
// atomic session
// - contains a static event queue for the asynchronous local event delivery;
// this queue is emptied by DmtAdminFactory, which forwards the events to all
// locally registered DmtEventListeners
class EventStore {
private static LinkedList localEventQueue = new LinkedList();
private static void postLocalEvent(DmtEventCore event) {
synchronized (localEventQueue) {
localEventQueue.addLast(event);
localEventQueue.notifyAll();
}
}
// Retrieve the next event from the queue. If there are no events, block
// until one is added, or until the given timeout time (in milliseconds) has
// elapsed. A timeout of zero blocks indefinitely. In case of timeout, or
// if the wait has been interrupted, the method returns "null".
static DmtEventCore getNextLocalEvent(int timeout) {
synchronized (localEventQueue) {
if(localEventQueue.size() == 0) {
try {
localEventQueue.wait(timeout);
} catch (InterruptedException e) {
// do nothing
}
if(localEventQueue.size() == 0)
return null;
}
return (DmtEventCore) localEventQueue.removeFirst();
}
}
private final int sessionId;
private final Context context;
private Hashtable events;
EventStore(Context context, int sessionId) {
this.sessionId = sessionId;
this.context = context;
events = new Hashtable();
}
synchronized void clear() {
events.clear();
}
synchronized void excludeRoot(Node root) {
Enumeration e = events.elements();
while (e.hasMoreElements())
((DmtEventCore) e.nextElement()).excludeRoot(root);
}
synchronized void add(int type, Node node, Node newNode, Acl acl,
boolean isAtomic) {
if (isAtomic) { // add event to event store, for delivery at commit
Integer typeInteger = new Integer(type);
DmtEventCore event = (DmtEventCore) events.get(typeInteger);
if(event == null) {
event = new DmtEventCore(type, sessionId);
events.put(typeInteger, event);
}
event.addNode(node, newNode, acl);
} else // dispatch to local and OSGi event listeners immediately
dispatchEvent(new DmtEventCore(type, sessionId, node, newNode, acl));
}
synchronized void dispatchEvents() {
dispatchEventsByType(DmtEvent.ADDED);
dispatchEventsByType(DmtEvent.DELETED);
dispatchEventsByType(DmtEvent.REPLACED);
dispatchEventsByType(DmtEvent.RENAMED);
dispatchEventsByType(DmtEvent.COPIED);
clear();
}
synchronized void dispatchEventsByType(int type) {
DmtEventCore event = (DmtEventCore) events.get(new Integer(type));
if(event != null)
dispatchEvent(event);
}
synchronized void dispatchSessionLifecycleEvent(int type) {
if(type != DmtEvent.SESSION_OPENED && type != DmtEvent.SESSION_CLOSED)
throw new IllegalArgumentException("Invalid event type, only " +
"session lifecycle events can be dispatched directly.");
dispatchEvent(new DmtEventCore(type, sessionId));
}
private void dispatchEvent(DmtEventCore dmtEvent) {
// send event to listeners directly registered with DmtAdmin
postLocalEvent(dmtEvent);
// send event to listeners registered through EventAdmin
postOSGiEvent(dmtEvent);
}
private void postOSGiEvent(DmtEventCore dmtEvent) {
final EventAdmin eventChannel =
(EventAdmin) context.getTracker(EventAdmin.class).getService();
if(eventChannel == null) {// logging a warning if Event Admin is missing
context.log(LogService.LOG_WARNING, "Event Admin not found, only " +
"delivering events to listeners directly registered with " +
"DmtAdmin.", null);
return;
}
Hashtable properties = new Hashtable();
properties.put("session.id", new Integer(dmtEvent.getSessionId()));
List nodes = dmtEvent.getNodes();
if(nodes != null)
properties.put("nodes",
Node.getUriArray((Node[]) nodes.toArray(new Node[0])));
List newNodes = dmtEvent.getNewNodes();
if(newNodes != null)
properties.put("newnodes",
Node.getUriArray((Node[]) newNodes.toArray(new Node[0])));
final Event event = new Event(dmtEvent.getTopic(), properties);
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
eventChannel.postEvent(event);
return null;
}
});
}
}
| - throwing exception if root node of session would be deleted or renamed
- not allowing execute in read-only sessions
- getting default value from MetaNode for interior nodes too
- sending SESSION_CLOSED events for abnormal session termination too
| org.osgi.impl.service.dmt/src/org/osgi/impl/service/dmt/DmtSessionImpl.java | - throwing exception if root node of session would be deleted or renamed - not allowing execute in read-only sessions - getting default value from MetaNode for interior nodes too - sending SESSION_CLOSED events for abnormal session termination too |
|
Java | apache-2.0 | 2b6039540060def2048c2936bc113c2d1d89e7ce | 0 | oboehm/gdv.xport,oboehm/gdv.xport,oboehm/gdv.xport | /*
* Copyright (c) 2017 by Oliver Boehm
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 15.02.17 by oliver ([email protected])
*/
package gdv.xport.srv.web;
import gdv.xport.srv.service.DatenpaketService;
import gdv.xport.srv.service.DefaultDatenpaketService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import patterntesting.runtime.log.LogWatch;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
import java.util.List;
/**
* Dieser Controller repraesentiert das REST-Interface zur Datenpaket-Klasse.
*
* @author <a href="[email protected]">oliver</a>
*/
@RestController
@RequestMapping("/Datenpakete")
public final class DatenpaketController {
private static final Logger LOG = LogManager.getLogger(DatenpaketController.class);
@Autowired
private DatenpaketService service;
/**
* Validiert die uebergebene URI.
*
* @param uri z.B. http://www.gdv-online.de/vuvm/musterdatei_bestand/musterdatei_041222.txt
* @return the response entity
*/
@GetMapping("/validate")
@ApiOperation(value = "validiert die uebergebene URI")
@ApiImplicitParams({
@ApiImplicitParam(
name = "uri",
value = "z.B. http://www.gdv-online.de/vuvm/musterdatei_bestand/musterdatei_041222.txt",
required = true,
dataType = "string",
paramType = "query"
)
})
public ResponseEntity<List<Model>> validate(@RequestParam("uri") URI uri) {
LogWatch watch = new LogWatch();
LOG.info("Validating Datenpakete in {}...", uri);
List<Model> violations = service.validate(uri);
LOG.info("Validating Datenpakete in {} finished with {} violation(s) in {}.", uri, violations.size(), watch);
return ResponseEntity.ok(violations);
}
/**
* Validiert die eingelesenen Datenpakete.
*
* @param body Text, der ueber die Leitung reinkommt.
* @param text alternativ kann der Text auch als Parameter reinkommen
* @return the response entity
*/
@PostMapping("/validate")
public ResponseEntity<List<Model>> validate(@RequestBody(required = false) String body, @RequestParam(required = false) String text) {
LogWatch watch = new LogWatch();
String content = (StringUtils.isBlank(text)) ? body : text;
LOG.info("Validating Datenpakete in posted stream of {} bytes...", StringUtils.length(content));
List<Model> violations = service.validate(content);
LOG.info("Validating Datenpakete in posted stream finished with {} violation(s) in {}.", violations.size(), watch);
return ResponseEntity.ok(violations);
}
/**
* Laedt die gewuenschte Datei und validiert die darin enthaltenen
* Datenpakete. Da hierueber der Inhalt der Datei mit uebertragen wird,
* wird dieser Service ueber POST angesprochen.
*
* @param file gewuenschte Datei
* @return the response entity
*/
@PostMapping("/validateUploaded")
public ResponseEntity<List<Model>> validate(@RequestParam("file") MultipartFile file) {
LogWatch watch = new LogWatch();
LOG.info("Validating Datenpakete in posted file '{}'...", file);
try {
String text = new String(file.getBytes());
List<Model> violations = service.validate(text);
LOG.info("Validating Datenpakete in {} finished with {} violation(s) in {}.", file, violations.size(), watch);
return ResponseEntity.ok(violations);
} catch (IOException ioe) {
LOG.warn("Cannot upload and validate {}:", file.getOriginalFilename(), ioe);
return ResponseEntity.badRequest().body(DefaultDatenpaketService.asModelList(ioe));
}
}
/**
* Formattiert das Datenpaket, das als Text reinkommt, in das gewuenschte
* Format wie HTML, XML, JSON oder CSV.
*
* @param body the body
* @param text the text
* @return the string
*/
@PostMapping(
value = "/format{suffix}",
produces = { MediaType.TEXT_HTML_VALUE, MediaType.TEXT_XML_VALUE, MediaType.APPLICATION_JSON_VALUE, "text/csv" }
)
public @ResponseBody String format(@RequestBody(required = false) String body,
@RequestParam(required = false) String text,
@PathVariable(required = false) String suffix,
HttpServletRequest request) {
LogWatch watch = new LogWatch();
String content = (StringUtils.isBlank(text)) ? body : text;
LOG.info("Formatting Datenpakete in posted stream of {} bytes...", StringUtils.length(content));
MimeType type = toMimeType(suffix, request);
String response = service.format(content, type);
LOG.info("Formatting Datenpakete in posted stream finished in {}.", watch);
return response;
}
private static MimeType toMimeType(String format, HttpServletRequest request) {
String fmt = format;
if (StringUtils.isBlank(format)) {
String[] accepted = request.getHeader("accept").split(",");
fmt = accepted[0];
}
fmt = fmt.toLowerCase();
if (fmt.contains("html")) {
return MediaType.TEXT_HTML;
} else {
LOG.info("Will use '{}' as MimeType for unknown format parameter '{}'.", MediaType.TEXT_PLAIN, fmt);
return MediaType.TEXT_PLAIN;
}
}
}
| service/src/main/java/gdv/xport/srv/web/DatenpaketController.java | /*
* Copyright (c) 2017 by Oliver Boehm
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 15.02.17 by oliver ([email protected])
*/
package gdv.xport.srv.web;
import gdv.xport.srv.service.DatenpaketService;
import gdv.xport.srv.service.DefaultDatenpaketService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import patterntesting.runtime.log.LogWatch;
import java.io.IOException;
import java.net.URI;
import java.util.List;
/**
* Dieser Controller repraesentiert das REST-Interface zur Datenpaket-Klasse.
*
* @author <a href="[email protected]">oliver</a>
*/
@RestController
@RequestMapping("/Datenpakete")
public final class DatenpaketController {
private static final Logger LOG = LogManager.getLogger(DatenpaketController.class);
@Autowired
private DatenpaketService service;
/**
* Validiert die uebergebene URI.
*
* @param uri z.B. http://www.gdv-online.de/vuvm/musterdatei_bestand/musterdatei_041222.txt
* @return the response entity
*/
@GetMapping("/validate")
@ApiOperation(value = "validiert die uebergebene URI")
@ApiImplicitParams({
@ApiImplicitParam(
name = "uri",
value = "z.B. http://www.gdv-online.de/vuvm/musterdatei_bestand/musterdatei_041222.txt",
required = true,
dataType = "string",
paramType = "query"
)
})
public ResponseEntity<List<Model>> validate(@RequestParam("uri") URI uri) {
LogWatch watch = new LogWatch();
LOG.info("Validating Datenpakete in {}...", uri);
List<Model> violations = service.validate(uri);
LOG.info("Validating Datenpakete in {} finished with {} violation(s) in {}.", uri, violations.size(), watch);
return ResponseEntity.ok(violations);
}
/**
* Validiert die eingelesenen Datenpakete.
*
* @param body Text, der ueber die Leitung reinkommt.
* @param text alternativ kann der Text auch als Parameter reinkommen
* @return the response entity
*/
@PostMapping("/validate")
public ResponseEntity<List<Model>> validate(@RequestBody(required = false) String body, @RequestParam(required = false) String text) {
LogWatch watch = new LogWatch();
String content = (StringUtils.isBlank(text)) ? body : text;
LOG.info("Validating Datenpakete in posted stream of {} bytes...", StringUtils.length(content));
List<Model> violations = service.validate(content);
LOG.info("Validating Datenpakete in posted stream finished with {} violation(s) in {}.", violations.size(), watch);
return ResponseEntity.ok(violations);
}
/**
* Laedt die gewuenschte Datei und validiert die darin enthaltenen
* Datenpakete. Da hierueber der Inhalt der Datei mit uebertragen wird,
* wird dieser Service ueber POST angesprochen.
*
* @param file gewuenschte Datei
* @return the response entity
*/
@PostMapping("/validateUploaded")
public ResponseEntity<List<Model>> validate(@RequestParam("file") MultipartFile file) {
LogWatch watch = new LogWatch();
LOG.info("Validating Datenpakete in posted file '{}'...", file);
try {
String text = new String(file.getBytes());
List<Model> violations = service.validate(text);
LOG.info("Validating Datenpakete in {} finished with {} violation(s) in {}.", file, violations.size(), watch);
return ResponseEntity.ok(violations);
} catch (IOException ioe) {
LOG.warn("Cannot upload and validate {}:", file.getOriginalFilename(), ioe);
return ResponseEntity.badRequest().body(DefaultDatenpaketService.asModelList(ioe));
}
}
/**
* Formattiert das Datenpaket, das als Text reinkommt, in das gewuenschte
* Format wie HTML, XML, JSON oder CSV.
*
* @param body the body
* @param text the text
* @return the string
*/
@PostMapping(
value = "/format",
produces = MediaType.TEXT_HTML_VALUE
//produces = { MediaType.TEXT_HTML_VALUE, MediaType.TEXT_XML_VALUE, MediaType.APPLICATION_JSON_VALUE, "text/csv" }
)
public @ResponseBody String format(@RequestBody(required = false) String body, @RequestParam(required = false) String text) {
LogWatch watch = new LogWatch();
String content = (StringUtils.isBlank(text)) ? body : text;
LOG.info("Formatting Datenpakete in posted stream of {} bytes...", StringUtils.length(content));
String response = service.format(content, MimeType.valueOf(MediaType.TEXT_HTML_VALUE));
LOG.info("Formatting Datenpakete in posted stream finished in {}.", watch);
return response;
}
}
| parsing request header to get accepted media format
| service/src/main/java/gdv/xport/srv/web/DatenpaketController.java | parsing request header to get accepted media format |
|
Java | apache-2.0 | 4cf4b94e741e1e0bfaac8e2820d8a93a8558fc25 | 0 | cristian-sulea/jatoo-exec | /*
* Copyright (C) 2014 Cristian Sulea ( http://cristian.sulea.net )
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jatoo.exec;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Handy class to ease the execution of operating system commands.
*
* TODO: WARNING: not tested on Linux
*
* @author <a href="http://cristian.sulea.net" rel="author">Cristian Sulea</a>
* @version 1.5, July 25, 2014
*/
public class CommandExecutor {
private final List<String> commandPrefix;
public CommandExecutor() {
String osName = System.getProperty("os.name");
//
// Linux systems (WARNING: not tested)
if (osName.equals("Linux")) {
commandPrefix = new ArrayList<String>(0);
}
//
// old Windows systems
else if (osName.equals("Windows 95") || osName.equals("Windows 98") || osName.equalsIgnoreCase("Windows ME")) {
commandPrefix = Arrays.asList("command.com", "/C");
}
//
// modern (others) Windows systems
else {
commandPrefix = Arrays.asList("cmd.exe", "/C");
}
}
/**
* Handy method for {@link #exec(String, File, OutputStream, boolean)} running
* in working folder of JVM with no dump output stream.
*
* @param command
* the command to be executed
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command) throws IOException, InterruptedException {
return exec(command, null, null, false);
}
/**
* Handy method for {@link #exec(String, File, OutputStream, boolean)} with no
* dump output stream.
*
* @param command
* the command to be executed
* @param folder
* the working folder
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command, final File folder) throws IOException, InterruptedException {
return exec(command, folder, null, false);
}
/**
* Handy method for {@link #exec(String, File, OutputStream, boolean)} running
* in working folder of JVM with specified dump output stream (but no
* closing).
*
* @param command
* the command to be executed
* @param dumpOutputStream
* the stream where the process will dump (exhaust) his contents
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command, final OutputStream dumpOutputStream) throws IOException, InterruptedException {
return exec(command, null, dumpOutputStream, false);
}
/**
* Handy method for {@link #exec(String, File, OutputStream, boolean)} with
* specified dump output stream (but no closing).
*
* @param command
* the command to be executed
* @param folder
* the working folder
* @param dumpOutputStream
* the stream where the process will dump (exhaust) his contents
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command, final File folder, final OutputStream dumpOutputStream) throws IOException, InterruptedException {
return exec(command, folder, dumpOutputStream, false);
}
/**
* Executes the specified command.
*
* @param command
* the command to be executed
* @param folder
* the working folder
*
* @param dumpOutputStream
* the stream where the process will dump (exhaust) his contents
* @param closeDumpOutputStream
* <code>true</code> if the dump stream should be closed when the
* execution ends, <code>false</code> otherwise
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command, final File folder, final OutputStream dumpOutputStream, final boolean closeDumpOutputStream) throws IOException, InterruptedException {
//
// add the prefix to the command
List<String> commandList = new ArrayList<String>(commandPrefix.size() + 1);
commandList.addAll(commandPrefix);
commandList.add(command);
//
// create and start the process
Process process = new ProcessBuilder(commandList).directory(folder).start();
//
// exhaust both the standard error stream and the standard output stream
if (dumpOutputStream != null) {
new Thread(new InputStreamExhausterWithDumpStream(process.getInputStream(), dumpOutputStream, closeDumpOutputStream)).start();
new Thread(new InputStreamExhausterWithDumpStream(process.getErrorStream(), dumpOutputStream, closeDumpOutputStream)).start();
} else {
new Thread(new InputStreamExhauster(process.getInputStream())).start();
new Thread(new InputStreamExhauster(process.getErrorStream())).start();
}
//
// wait until the process has terminated
return process.waitFor();
}
}
| jatoo-exec/src/main/java/jatoo/exec/CommandExecutor.java | /*
* Copyright (C) 2014 Cristian Sulea ( http://cristian.sulea.net )
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jatoo.exec;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Handy class to ease the execution of operating system commands.
*
* TODO: WARNING: not tested on Linux
*
* @author <a href="http://cristian.sulea.net" rel="author">Cristian Sulea</a>
* @version 1.5, July 25, 2014
*/
public class CommandExecutor {
private final List<String> commandPrefix;
public CommandExecutor() {
String osName = System.getProperty("os.name");
//
// Linux systems (WARNING: not tested)
if (osName.equals("Linux")) {
commandPrefix = new ArrayList<String>(0);
}
//
// old Windows systems
else if (osName.equals("Windows 95") || osName.equals("Windows 98") || osName.equalsIgnoreCase("Windows ME")) {
commandPrefix = Arrays.asList("command.com", "/C");
}
//
// modern (others) Windows systems
else {
commandPrefix = Arrays.asList("cmd.exe", "/C");
}
}
/**
* Handy method for {@link #exec(String, File, OutputStream, boolean)} running
* in working folder of JVM with no dump output stream.
*
* @param command
* the command to be executed
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command) throws IOException, InterruptedException {
return exec(command, null, null, false);
}
/**
* Handy method for {@link #exec(String, File, OutputStream, boolean)} with no
* dump output stream.
*
* @param command
* the command to be executed
* @param folder
* the working folder
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command, final File folder) throws IOException, InterruptedException {
return exec(command, null, null, false);
}
/**
* Handy method for {@link #exec(String, File, OutputStream, boolean)} running
* in working folder of JVM with specified dump output stream (but no
* closing).
*
* @param command
* the command to be executed
* @param dumpOutputStream
* the stream where the process will dump (exhaust) his contents
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command, final OutputStream dumpOutputStream) throws IOException, InterruptedException {
return exec(command, null, dumpOutputStream, false);
}
/**
* Handy method for {@link #exec(String, File, OutputStream, boolean)} with
* specified dump output stream (but no closing).
*
* @param command
* the command to be executed
* @param folder
* the working folder
* @param dumpOutputStream
* the stream where the process will dump (exhaust) his contents
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command, final File folder, final OutputStream dumpOutputStream) throws IOException, InterruptedException {
return exec(command, folder, dumpOutputStream, false);
}
/**
* Executes the specified command.
*
* @param command
* the command to be executed
* @param folder
* the working folder
*
* @param dumpOutputStream
* the stream where the process will dump (exhaust) his contents
* @param closeDumpOutputStream
* <code>true</code> if the dump stream should be closed when the
* execution ends, <code>false</code> otherwise
*
* @return the exit value of the process (by convention, the value
* <code>0</code> indicates normal termination)
*
* @throws IOException
* if an I/O error occurs
* @throws InterruptedException
* if the current thread is {@linkplain Thread#interrupt()
* interrupted} by another thread while it is waiting
*/
public final int exec(final String command, final File folder, final OutputStream dumpOutputStream, final boolean closeDumpOutputStream) throws IOException, InterruptedException {
//
// add the prefix to the command
List<String> commandList = new ArrayList<String>(commandPrefix.size() + 1);
commandList.addAll(commandPrefix);
commandList.add(command);
//
// create and start the process
Process process = new ProcessBuilder(commandList).directory(folder).start();
//
// exhaust both the standard error stream and the standard output stream
if (dumpOutputStream != null) {
new Thread(new InputStreamExhausterWithDumpStream(process.getInputStream(), dumpOutputStream, closeDumpOutputStream)).start();
new Thread(new InputStreamExhausterWithDumpStream(process.getErrorStream(), dumpOutputStream, closeDumpOutputStream)).start();
} else {
new Thread(new InputStreamExhauster(process.getInputStream())).start();
new Thread(new InputStreamExhauster(process.getErrorStream())).start();
}
//
// wait until the process has terminated
return process.waitFor();
}
}
| bug fix: the folder was ignored | jatoo-exec/src/main/java/jatoo/exec/CommandExecutor.java | bug fix: the folder was ignored |
|
Java | apache-2.0 | 9df1c22771695e3118296ba75226a0f02dff9531 | 0 | adaptris/interlok | /*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import com.adaptris.util.URLString;
/**
* <p>
* Defines methods required to 'marshal' Java objects to XML.
* </p>
*/
public interface AdaptrisMarshaller {
/**
* Marshalls an object to XML.
*
* @param obj the <code>Object</code> to marshall to XML
* @return a XML representation of the <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
String marshal(Object obj) throws CoreException;
/**
* Marshalls an object to XML.
*
* @param obj the <code>Object</code> to marshall to XML
* @param fileName the name of the file to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, String fileName) throws CoreException;
/**
* Marshalls an object to XML.
*
* @param obj the <code>Object</code> to marshall to XML
* @param file the file to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, File file) throws CoreException;
/**
* Marshalls an object to XML.
*
*
* @param obj the <code>Object</code> to marshall to XML
* @param writer the writer to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, Writer writer) throws CoreException;
/**
* Marshalls an object to XML.
*
*
* @param obj the object to marshall to XML
* @param outputStream the OutputStream to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, OutputStream outputStream) throws CoreException;
/**
* <p>
* Marshalls an XML representation of the passed <code>Object</code> to the
* file sytem location denoted by the passed <code>URL</code>.
* </p>
* @param obj the <code>Object</code> to marshall to XML
* @param fileUrl the file system location to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, URL fileUrl) throws CoreException;
/**
* <p>
* Unmarshalls an <code>Object</code> from the passed XML.
* </p>
* @param xml the <code>String</code> to unmarshal
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(String xml) throws CoreException;
/**
* <p>
* Unmarshalls an <code>Object</code> based on the passed <code>file</code>.
* </p>
* @param file a file containing XML to unmarshal
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(File file) throws CoreException;
/**
* <p>
* Unmarshalls an <code>Object</code> based on the passed file system
* <code>URL</code>.
* </p>
* @param fileUrl the file system location to read from
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(URL fileUrl) throws CoreException;
/**
* <p>
* Unmarshalls an <code>Object</code> based on the passed <code>Reader</code>.
* </p>
* @param reader a <code>Reader</code> with XML to unmarshal
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(Reader reader) throws CoreException;
/**
* <p>
* Unmarshals an <code>Object</code> based on the passed
* <code>InputStream</code>.
* </p>
* @param stream an <code>InputStream</code> of XML to unmarshal
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(InputStream stream) throws CoreException;
/**
* <p>
* Unmarshals an <code>Object</code> from the passed <code>URLString</code>
* location.
* </p>
* @param location the location to unmarshal from
* @return the unmarshalled <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>s
*/
Object unmarshal(URLString location) throws CoreException;
/**
* Convenience method to wrap marshalling activities with a RuntimeException .
*
* @since 3.8.2
*/
static void uncheckedMarshal(AdaptrisMarshaller m, Object o, MarshalOutputStream out) {
try (OutputStream autoClose = out.openStream()) {
m.marshal(o, autoClose);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Convenience method to wrap unmarshalling activities with a RuntimeException .
*
* @since 3.8.2
*/
static Object uncheckedUnmarshal(AdaptrisMarshaller m, Object o, MarshalInputStream in) {
try (InputStream autoClose = in.openStream()) {
return m.unmarshal(autoClose);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@FunctionalInterface
interface MarshalOutputStream {
OutputStream openStream() throws Exception;
}
@FunctionalInterface
interface MarshalInputStream {
InputStream openStream() throws Exception;
}
}
| interlok-core/src/main/java/com/adaptris/core/AdaptrisMarshaller.java | /*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import com.adaptris.util.URLString;
/**
* <p>
* Defines methods required to 'marshal' Java objects to XML.
* </p>
*/
public interface AdaptrisMarshaller {
/**
* Marshalls an object to XML.
*
* @param obj the <code>Object</code> to marshall to XML
* @return a XML representation of the <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
String marshal(Object obj) throws CoreException;
/**
* Marshalls an object to XML.
*
* @param obj the <code>Object</code> to marshall to XML
* @param fileName the name of the file to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, String fileName) throws CoreException;
/**
* Marshalls an object to XML.
*
* @param obj the <code>Object</code> to marshall to XML
* @param file the file to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, File file) throws CoreException;
/**
* Marshalls an object to XML.
*
*
* @param obj the <code>Object</code> to marshall to XML
* @param writer the writer to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, Writer writer) throws CoreException;
/**
* Marshalls an object to XML.
*
*
* @param obj the object to marshall to XML
* @param outputStream the OutputStream to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, OutputStream outputStream) throws CoreException;
/**
* <p>
* Marshalls an XML representation of the passed <code>Object</code> to the
* file sytem location denoted by the passed <code>URL</code>.
* </p>
* @param obj the <code>Object</code> to marshall to XML
* @param fileUrl the file system location to write to
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
void marshal(Object obj, URL fileUrl) throws CoreException;
/**
* <p>
* Unmarshalls an <code>Object</code> from the passed XML.
* </p>
* @param xml the <code>String</code> to unmarshal
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(String xml) throws CoreException;
/**
* <p>
* Unmarshalls an <code>Object</code> based on the passed <code>file</code>.
* </p>
* @param file a file containing XML to unmarshal
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(File file) throws CoreException;
/**
* <p>
* Unmarshalls an <code>Object</code> based on the passed file system
* <code>URL</code>.
* </p>
* @param fileUrl the file system location to read from
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(URL fileUrl) throws CoreException;
/**
* <p>
* Unmarshalls an <code>Object</code> based on the passed <code>Reader</code>.
* </p>
* @param reader a <code>Reader</code> with XML to unmarshal
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(Reader reader) throws CoreException;
/**
* <p>
* Unmarshals an <code>Object</code> based on the passed
* <code>InputStream</code>.
* </p>
* @param stream an <code>InputStream</code> of XML to unmarshal
* @return an <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>
*/
Object unmarshal(InputStream stream) throws CoreException;
/**
* <p>
* Unmarshals an <code>Object</code> from the passed <code>URLString</code>
* location.
* </p>
* @param location the location to unmarshal from
* @return the unmarshalled <code>Object</code>
* @throws CoreException wrapping any underlying <code>Exception</code>s
*/
Object unmarshal(URLString location) throws CoreException;
/**
* Convenience method to wrap marshalling activities with a RuntimeException .
*
* @since 3.8.2
*/
static void uncheckedMarshal(AdaptrisMarshaller m, Object o, MarshalOutputStream out) {
try (OutputStream autoClose = out.openStream()) {
m.marshal(o, autoClose);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Convenience method to wrap unmarshalling activities with a RuntimeException .
*
* @since 3.8.2
*/
static Object uncheckedUnmarshal(AdaptrisMarshaller m, Object o, MarshalInputStream in) {
try (InputStream autoClose = in.openStream()) {
return m.unmarshal(autoClose);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@FunctionalInterface
interface MarshalOutputStream {
OutputStream openStream();
}
@FunctionalInterface
interface MarshalInputStream {
InputStream openStream();
}
}
| Add Exception to openStream() as we wrap it anyway as a RTE
| interlok-core/src/main/java/com/adaptris/core/AdaptrisMarshaller.java | Add Exception to openStream() as we wrap it anyway as a RTE |
|
Java | apache-2.0 | 615b3d3985195392615aa64209b0eb04851313d8 | 0 | mglukhikh/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,xfournet/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,da1z/intellij-community,da1z/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,semonte/intellij-community,allotria/intellij-community,allotria/intellij-community,asedunov/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,allotria/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,allotria/intellij-community,youdonghai/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,asedunov/intellij-community,allotria/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,signed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,allotria/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,signed/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,signed/intellij-community,xfournet/intellij-community,allotria/intellij-community,signed/intellij-community,signed/intellij-community,da1z/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,da1z/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,asedunov/intellij-community,semonte/intellij-community,FHannes/intellij-community,allotria/intellij-community,xfournet/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,apixandru/intellij-community,semonte/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,signed/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,semonte/intellij-community,youdonghai/intellij-community,signed/intellij-community,signed/intellij-community,signed/intellij-community,da1z/intellij-community,signed/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,semonte/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ibinti/intellij-community,da1z/intellij-community,ibinti/intellij-community,asedunov/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,xfournet/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,FHannes/intellij-community | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util;
import com.intellij.codeInsight.highlighting.HighlightErrorFilter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.SyntaxTraverser;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import org.jetbrains.annotations.NotNull;
public class PsiErrorElementUtil {
private static final Key<CachedValue<Boolean>> CONTAINS_ERROR_ELEMENT = Key.create("CONTAINS_ERROR_ELEMENT");
private PsiErrorElementUtil() {}
public static boolean hasErrors(@NotNull Project project, @NotNull VirtualFile virtualFile) {
return ApplicationManager.getApplication().runReadAction((Computable<Boolean>)() -> {
if (project.isDisposed() || !virtualFile.isValid()) return false;
PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(project);
PsiFile psiFile = psiManager.getFileManager().findFile(virtualFile);
return psiFile != null && hasErrors(psiFile);
});
}
private static boolean hasErrors(@NotNull PsiFile psiFile) {
CachedValuesManager cachedValuesManager = CachedValuesManager.getManager(psiFile.getProject());
return cachedValuesManager.getCachedValue(
psiFile, CONTAINS_ERROR_ELEMENT,
() -> CachedValueProvider.Result.create(hasErrorElements(psiFile), psiFile),
false
);
}
private static boolean hasErrorElements(@NotNull PsiElement element) {
HighlightErrorFilter[] filters = null;
for (PsiErrorElement error : SyntaxTraverser.psiTraverser(element).traverse().filter(PsiErrorElement.class)) {
if (filters == null) {
filters = HighlightErrorFilter.EP_NAME.getExtensions(element.getProject());
}
if (shouldHighlightErrorElement(error, filters)) {
return true;
}
}
return false;
}
private static boolean shouldHighlightErrorElement(@NotNull PsiErrorElement error, @NotNull HighlightErrorFilter[] filters) {
for (HighlightErrorFilter filter : filters) {
if (!filter.shouldHighlightErrorElement(error)) {
return false;
}
}
return true;
}
}
| platform/platform-impl/src/com/intellij/util/PsiErrorElementUtil.java | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util;
import com.intellij.codeInsight.highlighting.HighlightErrorFilter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.SyntaxTraverser;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import org.jetbrains.annotations.NotNull;
public class PsiErrorElementUtil {
private static final Key<CachedValue<Boolean>> CONTAINS_ERROR_ELEMENT = Key.create("CONTAINS_ERROR_ELEMENT");
private PsiErrorElementUtil() {}
public static boolean hasErrors(@NotNull Project project, @NotNull VirtualFile virtualFile) {
return ApplicationManager.getApplication().runReadAction((Computable<Boolean>)() -> {
if (project.isDisposed() || !virtualFile.isValid()) return false;
PsiManagerEx psiManager = PsiManagerEx.getInstanceEx(project);
PsiFile psiFile = psiManager.getFileManager().findFile(virtualFile);
return psiFile != null && hasErrors(psiFile);
});
}
private static boolean hasErrors(@NotNull PsiFile psiFile) {
CachedValuesManager cachedValuesManager = CachedValuesManager.getManager(psiFile.getProject());
return cachedValuesManager.getCachedValue(
psiFile, CONTAINS_ERROR_ELEMENT,
() -> CachedValueProvider.Result.create(hasErrorElements(psiFile), psiFile),
false
);
}
private static boolean hasErrorElements(@NotNull PsiElement element) {
HighlightErrorFilter[] filters = null;
for (PsiErrorElement errorElement : SyntaxTraverser.psiTraverser(element).traverse().filter(PsiErrorElement.class)) {
if (filters == null) {
filters = HighlightErrorFilter.EP_NAME.getExtensions(element.getProject());
}
if (shouldHighlightErrorElement(errorElement, filters)) {
return true;
}
}
return false;
}
private static boolean shouldHighlightErrorElement(@NotNull PsiErrorElement error, @NotNull HighlightErrorFilter[] filters) {
for (HighlightErrorFilter filter : filters) {
if (!filter.shouldHighlightErrorElement(error)) {
return false;
}
}
return true;
}
}
| refactoring: shorter variable name (IDEA-CR-16497)
| platform/platform-impl/src/com/intellij/util/PsiErrorElementUtil.java | refactoring: shorter variable name (IDEA-CR-16497) |
|
Java | apache-2.0 | bb0ccc393321025644e02f24e2e4426af7a629ae | 0 | eFaps/eFaps-Kernel,ov3rflow/eFaps-Kernel | /*
* Copyright 2003 - 2009 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.update.datamodel;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.efaps.admin.datamodel.AttributeSet;
import org.efaps.admin.event.EventType;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.SearchQuery;
import org.efaps.db.Update;
import org.efaps.update.AbstractUpdate;
import org.efaps.update.LinkInstance;
import org.efaps.update.event.Event;
import org.efaps.util.EFapsException;
/**
* This Class is responsible for the Update of Type in the Database.<br>
* It reads with <code>org.apache.commons.digester</code> a XML-File to create
* the different Classes and invokes the Methods to Update a Type
*
* @author tmo
* @author jmox
* @version $Id$
*/
public class TypeUpdate extends AbstractUpdate
{
// ///////////////////////////////////////////////////////////////////////////
// static variables
/**
* Logging instance used to give logging information of this class.
*/
private final static Logger LOG = LoggerFactory.getLogger(TypeUpdate.class);
/**
* Link the data model type to allowed event types
*/
private final static Link LINK2ALLOWEDEVENT
= new Link("Admin_DataModel_TypeEventIsAllowedFor",
"To",
"Admin_DataModel_Type", "From");
/**
* List of all links for the type.
*/
private final static Set<Link> ALLLINKS = new HashSet<Link>();
static {
ALLLINKS.add(LINK2ALLOWEDEVENT);
}
/////////////////////////////////////////////////////////////////////////////
// constructors
/**
*
* @param _url URL of the file
*/
public TypeUpdate(final URL _url)
{
super(_url, "Admin_DataModel_Type", ALLLINKS);
}
/////////////////////////////////////////////////////////////////////////////
// intance methods
/**
* Creates new instance of class {@link TypeDefinition}.
*
* @return new definition instance
* @see TypeDefinition
*/
@Override
protected AbstractDefinition newDefinition()
{
return new TypeDefinition();
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/**
* The class defines an attribute of a type.
*/
public class AttributeDefinition extends AbstractDefinition
{
/** Name of the attribute. */
protected String name = null;
/** Name of the Attribute Type of the attribute. */
protected String type = null;
/** Name of the SQL Table of the attribute. */
protected String sqlTable = null;
/** SQL Column of the attribute. */
protected String sqlColumn = null;
/** Name of the Linked Type (used for links to another type). */
private String typeLink = null;
/** Events for this Attribute */
private final List<Event> events = new ArrayList<Event>();
/** default value for this Attribute */
private String defaultValue = null;
@Override
protected void readXML(final List<String> _tags,
final Map<String,String> _attributes,
final String _text)
{
final String value = _tags.get(0);
if ("defaultvalue".equals(value)) {
this.defaultValue = _text;
} else if ("name".equals(value)) {
this.name = _text;
} else if ("sqlcolumn".equals(value)) {
this.sqlColumn = _text;
} else if ("sqltable".equals(value)) {
this.sqlTable = _text;
} else if ("trigger".equals(value)) {
if (_tags.size() == 1) {
this.events.add(new Event(_attributes.get("name"),
EventType.valueOf(_attributes.get("event")),
_attributes.get("program"),
_attributes.get("method"),
_attributes.get("index")));
} else if ((_tags.size() == 2) && "property".equals(_tags.get(1))) {
this.events.get(this.events.size() - 1).addProperty(_attributes.get("name"),
_text);
} else {
super.readXML(_tags, _attributes, _text);
}
} else if ("type".equals(value)) {
this.type = _text;
} else if ("typelink".equals(value)) {
this.typeLink = _text;
} else if ("validate".equals(value)) {
if (_tags.size() == 1) {
this.events.add(new Event(_attributes.get("name"),
EventType.VALIDATE,
_attributes.get("program"),
_attributes.get("method"),
_attributes.get("index")));
} else if ((_tags.size() == 2) && "property".equals(_tags.get(1))) {
this.events.get(this.events.size() - 1).addProperty(_attributes.get("name"),
_text);
} else {
super.readXML(_tags, _attributes, _text);
}
} else {
super.readXML(_tags, _attributes, _text);
}
}
@Override
public void addEvent(final Event _event) {
this.events.add(_event);
}
/**
* For given type defined with the instance parameter, this attribute is
* searched by name. If the attribute exists, the attribute is updated.
* Otherwise the attribute is created for this type.
*
* @param _instance type instance to update with this attribute
* @param _typeName name of the type to update
* @param _attrInstanceId
* @see #getAttrTypeId
* @see #getSqlTableId
* @see #getTypeLinkId
* @todo throw Exception is not allowed
*/
protected void updateInDB(final Instance _instance,
final String _typeName,
final long _setID)
throws EFapsException
{
final long attrTypeId = getAttrTypeId(_typeName);
final long sqlTableId = getSqlTableId(_typeName);
final long typeLinkId = getTypeLinkId(_typeName);
final String type;
if (_setID>0) {
type = "Admin_DataModel_AttributeSetAttribute";
} else {
type = "Admin_DataModel_Attribute";
}
final SearchQuery query = new SearchQuery();
query.setQueryTypes(type);
query.addWhereExprEqValue("Name", this.name);
query.addWhereExprEqValue("ParentType", _instance.getId());
query.addSelect("OID");
query.executeWithoutAccessCheck();
Update update;
if (query.next()) {
update = new Update((String) query.get("OID"));
} else {
update = new Insert(type);
update.add("ParentType", "" + _instance.getId());
update.add("Name", this.name);
}
query.close();
update.add("AttributeType", "" + attrTypeId);
update.add("Table", "" + sqlTableId);
update.add("SQLColumn", this.sqlColumn);
if (typeLinkId == 0) {
update.add("TypeLink", (String) null);
} else {
update.add("TypeLink", "" + typeLinkId);
}
if (this.defaultValue != null) {
update.add("DefaultValue", this.defaultValue);
}
if (_setID!=0){
update.add("ParentAttributeSet","" + _setID);
}
update.executeWithoutAccessCheck();
for (final Event event : this.events) {
final Instance newInstance =
event.updateInDB(update.getInstance(), this.name);
setPropertiesInDb(newInstance, event.getProperties());
}
}
/**
* Makes a search query to return the id of the attribute type defined in
* {@link #type}.
*
* @return id of the attribute type
* @see #type
*/
protected long getAttrTypeId(final String _typeName)
throws EFapsException
{
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_AttributeType");
query.addWhereExprEqValue("Name", this.type);
query.addSelect("OID");
query.executeWithoutAccessCheck();
if (!query.next()) {
LOG.error("type["
+ _typeName
+ "]."
+ "attribute["
+ this.name
+ "]: "
+ "attribute type '"
+ this.type
+ "' not found");
}
final long attrTypeId = (new Instance((String) query.get("OID"))).getId();
query.close();
return attrTypeId;
}
/**
* Makes a search query to return the id of the SQL table defined in
* {@link #sqlTable}.
*
* @return id of the SQL table
* @see #sqlTable
*/
protected long getSqlTableId(final String _typeName)
throws EFapsException
{
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_SQLTable");
query.addWhereExprEqValue("Name", this.sqlTable);
query.addSelect("OID");
query.executeWithoutAccessCheck();
if (!query.next()) {
LOG.error("type["
+ _typeName
+ "]."
+ "attribute["
+ this.name
+ "]: "
+ "SQL table '"
+ this.sqlTable
+ "' not found");
}
final long sqlTableId = (new Instance((String) query.get("OID"))).getId();
query.close();
return sqlTableId;
}
/**
* Makes a search query to return the id of the SQL table defined in
* {@link #typeLink}.
*
* @return id of the linked type (or 0 if no type link is defined)
* @see #typeLink
*/
private long getTypeLinkId(final String _typeName)
throws EFapsException
{
long typeLinkId = 0;
if ((this.typeLink != null) && (this.typeLink.length() > 0)) {
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_Type");
query.addWhereExprEqValue("Name", this.typeLink);
query.addSelect("ID");
query.executeWithoutAccessCheck();
if (query.next()) {
typeLinkId = (Long) query.get("ID");
} else {
LOG.error("type["
+ _typeName
+ "]."
+ "attribute["
+ this.name
+ "]: "
+ " Type '"
+ this.typeLink
+ "' as link not found");
}
query.close();
}
return typeLinkId;
}
/**
* Returns a string representation with values of all instance variables of
* an attribute.
*
* @return string representation of this definition of an attribute
*/
@Override
public String toString()
{
return new ToStringBuilder(this)
.append("name", this.name)
.append("type", this.type)
.append("sqlTable", this.sqlTable)
.append("sqlColumn", this.sqlColumn)
.append("typeLink", this.typeLink)
.toString();
}
}
public class AttributeSetDefinition extends AttributeDefinition {
/**
* Current read attribute definition instance.
*
* @see #readXML(List, Map, String)
*/
private AttributeDefinition curAttr = null;
private final List<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>();
private String parentType;
/**
* @param _tags
* @param _attributes
* @param _text
*/
@Override
public void readXML(final List<String> _tags,
final Map<String, String> _attributes,
final String _text) {
final String value = _tags.get(0);
if ("name".equals(value)) {
this.name = _text;
} else if ("type".equals(value)) {
this.type = _text;
} else if ("parent".equals(value)) {
this.parentType = _text;
} else if ("sqltable".equals(value)) {
this.sqlTable = _text;
} else if ("sqlcolumn".equals(value)) {
this.sqlColumn = _text;
} else if ("attribute".equals(value)) {
if (_tags.size() == 1) {
this.curAttr = new AttributeDefinition();
this.attributes.add(this.curAttr);
} else {
this.curAttr.readXML(_tags.subList(1, _tags.size()), _attributes, _text);
}
} else {
super.readXML(_tags, _attributes, _text);
}
}
protected long getParentTypeId(final String _typeName)
throws EFapsException
{
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_Type");
query.addWhereExprEqValue("Name", _typeName);
query.addSelect("OID");
query.executeWithoutAccessCheck();
if (!query.next()) {
LOG.error("type["
+ _typeName
+ "]."
+ "attribute["
+ this.name
+ "]: "
+ "Parent TYpe '"
+ this.parentType
+ "' not found");
}
final long typeId = (new Instance((String) query.get("OID"))).getId();
query.close();
return typeId;
}
/**
* @param instance
* @param value
* @throws EFapsException
*/
public void updateInDB(final Instance _instance, final String _typeName) throws EFapsException {
final String name = AttributeSet.evaluateName(_typeName, this.name);
long parentTypeId = 0;
if (this.parentType!=null) {
parentTypeId = getParentTypeId(this.parentType);
}
final long attrTypeId = getAttrTypeId(_typeName);
final long sqlTableId = getSqlTableId(_typeName);
//create/update the attributSet
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_AttributeSet");
query.addWhereExprEqValue("Name", this.name);
query.addWhereExprEqValue("ParentType", _instance.getId());
query.addSelect("OID");
query.executeWithoutAccessCheck();
Update update = null;
if (query.next()) {
update = new Update((String) query.get("OID"));
} else {
update = new Insert("Admin_DataModel_AttributeSet");
update.add("ParentType", "" + _instance.getId());
update.add("Name", this.name);
}
query.close();
update.add("AttributeType", "" + attrTypeId);
update.add("Table", "" + sqlTableId);
update.add("SQLColumn", this.sqlColumn);
if (parentTypeId > 0){
update.add("TypeLink", "" + parentTypeId);
}
update.executeWithoutAccessCheck();
final long setId = update.getInstance().getId();
update.close();
// add the attributes to the new Type
for (final AttributeDefinition attr : this.attributes) {
attr.updateInDB(_instance, name, setId);
}
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// class for the definitions
public class TypeDefinition extends AbstractDefinition {
///////////////////////////////////////////////////////////////////////////
// instance variables
/**
* Stores the name of the parent type. The parent type could not be
* evaluated because it could be that the type does not exists (and so the
* type id is evaluated before the insert / update from method
* {@link #updateInDB}).
*
* @see #setParent
* @see #updateInDB
*/
private String parentType = null;
/**
* All attributes of the type are stored in this list.
*
* @see #updateInDB
* @see #addAttribute
*/
private final List<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>();
private final List<AttributeSetDefinition> attributeSets = new ArrayList<AttributeSetDefinition>();
/**
* Current read attribute definition instance.
*
* @see #readXML(List, Map, String)
*/
private AttributeDefinition curAttr = null;
private AttributeSetDefinition curAttrSet = null;
///////////////////////////////////////////////////////////////////////////
// instance methods
@Override
protected void readXML(final List<String> _tags,
final Map<String,String> _attributes,
final String _text)
{
final String value = _tags.get(0);
if ("abstract".equals(value)) {
addValue("Abstract", _text);
} else if ("attribute".equals(value)) {
if (_tags.size() == 1) {
this.curAttr = new AttributeDefinition();
this.attributes.add(this.curAttr);
} else {
this.curAttr.readXML(_tags.subList(1, _tags.size()), _attributes, _text);
}
} else if ("attributeset".equals(value)) {
if (_tags.size() == 1) {
this.curAttrSet = new AttributeSetDefinition();
this.attributeSets.add(this.curAttrSet);
} else {
this.curAttrSet.readXML(_tags.subList(1, _tags.size()), _attributes, _text);
}
}else if ("event-for".equals(value)) {
// Adds the name of a allowed event type
addLink(LINK2ALLOWEDEVENT, new LinkInstance(_attributes.get("type")));
} else if ("parent".equals(value)) {
this.parentType = _text;
} else if ("trigger".equals(value)) {
if (_tags.size() == 1) {
this.events.add(new Event(_attributes.get("name"),
EventType.valueOf(_attributes.get("event")),
_attributes.get("program"),
_attributes.get("method"),
_attributes.get("index")));
} else if ((_tags.size() == 2) && "property".equals(_tags.get(1))) {
this.events.get(this.events.size() - 1).addProperty(_attributes.get("name"),
_text);
} else {
super.readXML(_tags, _attributes, _text);
}
} else {
super.readXML(_tags, _attributes, _text);
}
}
/**
* If a parent type in {@link #parentType} is defined, the type id is
* evaluated and added to attributes to update (if no parent type is
* defined, the parent type id is set to <code>null</code>). After the
* type is updated (or inserted if needed), all attributes must be updated.
*
* @todo throw Exception is not allowed
* @see #parentType
* @see #attributes
*/
@Override
public void updateInDB(final Set<Link> _allLinkTypes)
throws EFapsException
{
// set the id of the parent type (if defined)
if ((this.parentType != null) && (this.parentType.length() > 0)) {
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_Type");
query.addWhereExprEqValue("Name", this.parentType);
query.addSelect("OID");
query.executeWithoutAccessCheck();
if (query.next()) {
final Instance instance = new Instance((String) query.get("OID"));
addValue("ParentType", "" + instance.getId());
} else {
addValue("ParentType", null);
}
query.close();
} else {
addValue("ParentType", null);
}
super.updateInDB(_allLinkTypes);
for (final AttributeDefinition attr : this.attributes) {
attr.updateInDB(this.instance, getValue("Name"), 0);
}
for (final AttributeSetDefinition attrSet : this.attributeSets) {
attrSet.updateInDB(this.instance, getValue("Name"));
}
}
}
}
| kernel/src/main/java/org/efaps/update/datamodel/TypeUpdate.java | /*
* Copyright 2003-2008 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.update.datamodel;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.efaps.admin.datamodel.AttributeSet;
import org.efaps.admin.event.EventType;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.SearchQuery;
import org.efaps.db.Update;
import org.efaps.update.AbstractUpdate;
import org.efaps.update.LinkInstance;
import org.efaps.update.event.Event;
import org.efaps.util.EFapsException;
/**
* This Class is responsible for the Update of Type in the Database.<br>
* It reads with <code>org.apache.commons.digester</code> a XML-File to create
* the different Classes and invokes the Methods to Update a Type
*
* @author tmo
* @author jmox
* @version $Id$
*/
public class TypeUpdate extends AbstractUpdate
{
// ///////////////////////////////////////////////////////////////////////////
// static variables
/**
* Logging instance used to give logging information of this class.
*/
private final static Logger LOG = LoggerFactory.getLogger(TypeUpdate.class);
/**
* Link the data model type to allowed event types
*/
private final static Link LINK2ALLOWEDEVENT
= new Link("Admin_DataModel_TypeEventIsAllowedFor",
"To",
"Admin_DataModel_Type", "From");
/**
* List of all links for the type.
*/
private final static Set<Link> ALLLINKS = new HashSet<Link>();
static {
ALLLINKS.add(LINK2ALLOWEDEVENT);
}
/////////////////////////////////////////////////////////////////////////////
// constructors
/**
*
* @param _url URL of the file
*/
public TypeUpdate(final URL _url)
{
super(_url, "Admin_DataModel_Type", ALLLINKS);
}
/////////////////////////////////////////////////////////////////////////////
// intance methods
/**
* Creates new instance of class {@link TypeDefinition}.
*
* @return new definition instance
* @see TypeDefinition
*/
@Override
protected AbstractDefinition newDefinition()
{
return new TypeDefinition();
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/**
* The class defines an attribute of a type.
*/
public class AttributeDefinition extends AbstractDefinition
{
/** Name of the attribute. */
protected String name = null;
/** Name of the Attribute Type of the attribute. */
protected String type = null;
/** Name of the SQL Table of the attribute. */
protected String sqlTable = null;
/** SQL Column of the attribute. */
protected String sqlColumn = null;
/** Name of the Linked Type (used for links to another type). */
private String typeLink = null;
/** Events for this Attribute */
private final List<Event> events = new ArrayList<Event>();
/** default value for this Attribute */
private String defaultValue = null;
@Override
protected void readXML(final List<String> _tags,
final Map<String,String> _attributes,
final String _text)
{
final String value = _tags.get(0);
if ("defaultvalue".equals(value)) {
} else if ("name".equals(value)) {
this.name = _text;
} else if ("sqlcolumn".equals(value)) {
this.sqlColumn = _text;
} else if ("sqltable".equals(value)) {
this.sqlTable = _text;
} else if ("trigger".equals(value)) {
if (_tags.size() == 1) {
this.events.add(new Event(_attributes.get("name"),
EventType.valueOf(_attributes.get("event")),
_attributes.get("program"),
_attributes.get("method"),
_attributes.get("index")));
} else if ((_tags.size() == 2) && "property".equals(_tags.get(1))) {
this.events.get(this.events.size() - 1).addProperty(_attributes.get("name"),
_text);
} else {
super.readXML(_tags, _attributes, _text);
}
} else if ("type".equals(value)) {
this.type = _text;
} else if ("typelink".equals(value)) {
this.typeLink = _text;
} else if ("validate".equals(value)) {
if (_tags.size() == 1) {
this.events.add(new Event(_attributes.get("name"),
EventType.VALIDATE,
_attributes.get("program"),
_attributes.get("method"),
_attributes.get("index")));
} else if ((_tags.size() == 2) && "property".equals(_tags.get(1))) {
this.events.get(this.events.size() - 1).addProperty(_attributes.get("name"),
_text);
} else {
super.readXML(_tags, _attributes, _text);
}
} else {
super.readXML(_tags, _attributes, _text);
}
}
/**
*
* @param _name
* @param _type
* @param _sqltable
* @param _sqlcolumn
* @param _typelink
* @param _defaultvalue
*/
public void setDefinitions(final String _name,
final String _type,
final String _sqltable,
final String _sqlcolumn,
final String _typelink,
final String _defaultvalue)
{
this.name = _name;
this.type = _type;
this.sqlTable = _sqltable;
this.sqlColumn = _sqlcolumn;
this.typeLink = _typelink;
this.defaultValue = _defaultvalue;
}
@Override
public void addEvent(final Event _event) {
this.events.add(_event);
}
/**
* For given type defined with the instance parameter, this attribute is
* searched by name. If the attribute exists, the attribute is updated.
* Otherwise the attribute is created for this type.
*
* @param _instance type instance to update with this attribute
* @param _typeName name of the type to update
* @param _attrInstanceId
* @see #getAttrTypeId
* @see #getSqlTableId
* @see #getTypeLinkId
* @todo throw Exception is not allowed
*/
protected void updateInDB(final Instance _instance,
final String _typeName,
final long _setID)
throws EFapsException
{
final long attrTypeId = getAttrTypeId(_typeName);
final long sqlTableId = getSqlTableId(_typeName);
final long typeLinkId = getTypeLinkId(_typeName);
final String type;
if (_setID>0) {
type = "Admin_DataModel_AttributeSetAttribute";
} else {
type = "Admin_DataModel_Attribute";
}
final SearchQuery query = new SearchQuery();
query.setQueryTypes(type);
query.addWhereExprEqValue("Name", this.name);
query.addWhereExprEqValue("ParentType", _instance.getId());
query.addSelect("OID");
query.executeWithoutAccessCheck();
Update update;
if (query.next()) {
update = new Update((String) query.get("OID"));
} else {
update = new Insert(type);
update.add("ParentType", "" + _instance.getId());
update.add("Name", this.name);
}
query.close();
update.add("AttributeType", "" + attrTypeId);
update.add("Table", "" + sqlTableId);
update.add("SQLColumn", this.sqlColumn);
if (typeLinkId == 0) {
update.add("TypeLink", (String) null);
} else {
update.add("TypeLink", "" + typeLinkId);
}
if (this.defaultValue != null) {
update.add("DefaultValue", this.defaultValue);
}
if (_setID!=0){
update.add("ParentAttributeSet","" + _setID);
}
update.executeWithoutAccessCheck();
for (final Event event : this.events) {
final Instance newInstance =
event.updateInDB(update.getInstance(), this.name);
setPropertiesInDb(newInstance, event.getProperties());
}
}
/**
* Makes a search query to return the id of the attribute type defined in
* {@link #type}.
*
* @return id of the attribute type
* @see #type
*/
protected long getAttrTypeId(final String _typeName)
throws EFapsException
{
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_AttributeType");
query.addWhereExprEqValue("Name", this.type);
query.addSelect("OID");
query.executeWithoutAccessCheck();
if (!query.next()) {
LOG.error("type["
+ _typeName
+ "]."
+ "attribute["
+ this.name
+ "]: "
+ "attribute type '"
+ this.type
+ "' not found");
}
final long attrTypeId = (new Instance((String) query.get("OID"))).getId();
query.close();
return attrTypeId;
}
/**
* Makes a search query to return the id of the SQL table defined in
* {@link #sqlTable}.
*
* @return id of the SQL table
* @see #sqlTable
*/
protected long getSqlTableId(final String _typeName)
throws EFapsException
{
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_SQLTable");
query.addWhereExprEqValue("Name", this.sqlTable);
query.addSelect("OID");
query.executeWithoutAccessCheck();
if (!query.next()) {
LOG.error("type["
+ _typeName
+ "]."
+ "attribute["
+ this.name
+ "]: "
+ "SQL table '"
+ this.sqlTable
+ "' not found");
}
final long sqlTableId = (new Instance((String) query.get("OID"))).getId();
query.close();
return sqlTableId;
}
/**
* Makes a search query to return the id of the SQL table defined in
* {@link #typeLink}.
*
* @return id of the linked type (or 0 if no type link is defined)
* @see #typeLink
*/
private long getTypeLinkId(final String _typeName)
throws EFapsException
{
long typeLinkId = 0;
if ((this.typeLink != null) && (this.typeLink.length() > 0)) {
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_Type");
query.addWhereExprEqValue("Name", this.typeLink);
query.addSelect("ID");
query.executeWithoutAccessCheck();
if (query.next()) {
typeLinkId = (Long) query.get("ID");
} else {
LOG.error("type["
+ _typeName
+ "]."
+ "attribute["
+ this.name
+ "]: "
+ " Type '"
+ this.typeLink
+ "' as link not found");
}
query.close();
}
return typeLinkId;
}
/**
* Returns a string representation with values of all instance variables of
* an attribute.
*
* @return string representation of this definition of an attribute
*/
@Override
public String toString()
{
return new ToStringBuilder(this)
.append("name", this.name)
.append("type", this.type)
.append("sqlTable", this.sqlTable)
.append("sqlColumn", this.sqlColumn)
.append("typeLink", this.typeLink)
.toString();
}
}
public class AttributeSetDefinition extends AttributeDefinition {
/**
* Current read attribute definition instance.
*
* @see #readXML(List, Map, String)
*/
private AttributeDefinition curAttr = null;
private final List<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>();
private String parentType;
/**
* @param _tags
* @param _attributes
* @param _text
*/
@Override
public void readXML(final List<String> _tags,
final Map<String, String> _attributes,
final String _text) {
final String value = _tags.get(0);
if ("name".equals(value)) {
this.name = _text;
} else if ("type".equals(value)) {
this.type = _text;
} else if ("parent".equals(value)) {
this.parentType = _text;
} else if ("sqltable".equals(value)) {
this.sqlTable = _text;
} else if ("sqlcolumn".equals(value)) {
this.sqlColumn = _text;
} else if ("attribute".equals(value)) {
if (_tags.size() == 1) {
this.curAttr = new AttributeDefinition();
this.attributes.add(this.curAttr);
} else {
this.curAttr.readXML(_tags.subList(1, _tags.size()), _attributes, _text);
}
} else {
super.readXML(_tags, _attributes, _text);
}
}
protected long getParentTypeId(final String _typeName)
throws EFapsException
{
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_Type");
query.addWhereExprEqValue("Name", _typeName);
query.addSelect("OID");
query.executeWithoutAccessCheck();
if (!query.next()) {
LOG.error("type["
+ _typeName
+ "]."
+ "attribute["
+ this.name
+ "]: "
+ "Parent TYpe '"
+ this.parentType
+ "' not found");
}
final long typeId = (new Instance((String) query.get("OID"))).getId();
query.close();
return typeId;
}
/**
* @param instance
* @param value
* @throws EFapsException
*/
public void updateInDB(final Instance _instance, final String _typeName) throws EFapsException {
final String name = AttributeSet.evaluateName(_typeName, this.name);
long parentTypeId = 0;
if (this.parentType!=null) {
parentTypeId = getParentTypeId(this.parentType);
}
final long attrTypeId = getAttrTypeId(_typeName);
final long sqlTableId = getSqlTableId(_typeName);
//create/update the attributSet
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_AttributeSet");
query.addWhereExprEqValue("Name", this.name);
query.addWhereExprEqValue("ParentType", _instance.getId());
query.addSelect("OID");
query.executeWithoutAccessCheck();
Update update = null;
if (query.next()) {
update = new Update((String) query.get("OID"));
} else {
update = new Insert("Admin_DataModel_AttributeSet");
update.add("ParentType", "" + _instance.getId());
update.add("Name", this.name);
}
query.close();
update.add("AttributeType", "" + attrTypeId);
update.add("Table", "" + sqlTableId);
update.add("SQLColumn", this.sqlColumn);
if (parentTypeId > 0){
update.add("TypeLink", "" + parentTypeId);
}
update.executeWithoutAccessCheck();
final long setId = update.getInstance().getId();
update.close();
// add the attributes to the new Type
for (final AttributeDefinition attr : this.attributes) {
attr.updateInDB(_instance, name, setId);
}
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// class for the definitions
public class TypeDefinition extends AbstractDefinition {
///////////////////////////////////////////////////////////////////////////
// instance variables
/**
* Stores the name of the parent type. The parent type could not be
* evaluated because it could be that the type does not exists (and so the
* type id is evaluated before the insert / update from method
* {@link #updateInDB}).
*
* @see #setParent
* @see #updateInDB
*/
private String parentType = null;
/**
* All attributes of the type are stored in this list.
*
* @see #updateInDB
* @see #addAttribute
*/
private final List<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>();
private final List<AttributeSetDefinition> attributeSets = new ArrayList<AttributeSetDefinition>();
/**
* Current read attribute definition instance.
*
* @see #readXML(List, Map, String)
*/
private AttributeDefinition curAttr = null;
private AttributeSetDefinition curAttrSet = null;
///////////////////////////////////////////////////////////////////////////
// instance methods
@Override
protected void readXML(final List<String> _tags,
final Map<String,String> _attributes,
final String _text)
{
final String value = _tags.get(0);
if ("abstract".equals(value)) {
addValue("Abstract", _text);
} else if ("attribute".equals(value)) {
if (_tags.size() == 1) {
this.curAttr = new AttributeDefinition();
this.attributes.add(this.curAttr);
} else {
this.curAttr.readXML(_tags.subList(1, _tags.size()), _attributes, _text);
}
} else if ("attributeset".equals(value)) {
if (_tags.size() == 1) {
this.curAttrSet = new AttributeSetDefinition();
this.attributeSets.add(this.curAttrSet);
} else {
this.curAttrSet.readXML(_tags.subList(1, _tags.size()), _attributes, _text);
}
}else if ("event-for".equals(value)) {
// Adds the name of a allowed event type
addLink(LINK2ALLOWEDEVENT, new LinkInstance(_attributes.get("type")));
} else if ("parent".equals(value)) {
this.parentType = _text;
} else if ("trigger".equals(value)) {
if (_tags.size() == 1) {
this.events.add(new Event(_attributes.get("name"),
EventType.valueOf(_attributes.get("event")),
_attributes.get("program"),
_attributes.get("method"),
_attributes.get("index")));
} else if ((_tags.size() == 2) && "property".equals(_tags.get(1))) {
this.events.get(this.events.size() - 1).addProperty(_attributes.get("name"),
_text);
} else {
super.readXML(_tags, _attributes, _text);
}
} else {
super.readXML(_tags, _attributes, _text);
}
}
/**
* If a parent type in {@link #parentType} is defined, the type id is
* evaluated and added to attributes to update (if no parent type is
* defined, the parent type id is set to <code>null</code>). After the
* type is updated (or inserted if needed), all attributes must be updated.
*
* @todo throw Exception is not allowed
* @see #parentType
* @see #attributes
*/
@Override
public void updateInDB(final Set<Link> _allLinkTypes)
throws EFapsException
{
// set the id of the parent type (if defined)
if ((this.parentType != null) && (this.parentType.length() > 0)) {
final SearchQuery query = new SearchQuery();
query.setQueryTypes("Admin_DataModel_Type");
query.addWhereExprEqValue("Name", this.parentType);
query.addSelect("OID");
query.executeWithoutAccessCheck();
if (query.next()) {
final Instance instance = new Instance((String) query.get("OID"));
addValue("ParentType", "" + instance.getId());
} else {
addValue("ParentType", null);
}
query.close();
} else {
addValue("ParentType", null);
}
super.updateInDB(_allLinkTypes);
for (final AttributeDefinition attr : this.attributes) {
attr.updateInDB(this.instance, getValue("Name"), 0);
}
for (final AttributeSetDefinition attrSet : this.attributeSets) {
attrSet.updateInDB(this.instance, getValue("Name"));
}
}
}
}
| - BugFix the default value was not evaluated
git-svn-id: 4b3b87045ec33e1a2f7ddff44705baa56df11711@2084 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
| kernel/src/main/java/org/efaps/update/datamodel/TypeUpdate.java | - BugFix the default value was not evaluated |
|
Java | apache-2.0 | 90178945e73961f4e0b33731916f4a6e569a1050 | 0 | xiangyong/httl,sdgdsffdsfff/httl,fengshao0907/httl,httl/httl | /*
* Copyright 2011-2013 HTTL Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package httl.spi.translators.templates;
import httl.Context;
import httl.Engine;
import httl.Node;
import httl.Resource;
import httl.Template;
import httl.ast.AddOperator;
import httl.ast.AndOperator;
import httl.ast.ArrayOperator;
import httl.ast.AstVisitor;
import httl.ast.BinaryOperator;
import httl.ast.BitAndOperator;
import httl.ast.BitNotOperator;
import httl.ast.BitOrOperator;
import httl.ast.BitXorOperator;
import httl.ast.BreakDirective;
import httl.ast.CastOperator;
import httl.ast.ConditionOperator;
import httl.ast.Constant;
import httl.ast.DivOperator;
import httl.ast.ElseDirective;
import httl.ast.EntryOperator;
import httl.ast.EqualsOperator;
import httl.ast.Expression;
import httl.ast.ForDirective;
import httl.ast.GreaterEqualsOperator;
import httl.ast.GreaterOperator;
import httl.ast.IfDirective;
import httl.ast.IndexOperator;
import httl.ast.InstanceofOperator;
import httl.ast.LeftShiftOperator;
import httl.ast.LessEqualsOperator;
import httl.ast.LessOperator;
import httl.ast.ListOperator;
import httl.ast.MacroDirective;
import httl.ast.MethodOperator;
import httl.ast.ModOperator;
import httl.ast.MulOperator;
import httl.ast.NegativeOperator;
import httl.ast.NewOperator;
import httl.ast.NotEqualsOperator;
import httl.ast.NotOperator;
import httl.ast.Operator;
import httl.ast.OrOperator;
import httl.ast.PositiveOperator;
import httl.ast.RightShiftOperator;
import httl.ast.SequenceOperator;
import httl.ast.SetDirective;
import httl.ast.Statement;
import httl.ast.StaticMethodOperator;
import httl.ast.SubOperator;
import httl.ast.Text;
import httl.ast.UnsignShiftOperator;
import httl.ast.ValueDirective;
import httl.ast.Variable;
import httl.spi.Compiler;
import httl.spi.Converter;
import httl.spi.Filter;
import httl.spi.Formatter;
import httl.spi.Interceptor;
import httl.spi.Switcher;
import httl.spi.formatters.MultiFormatter;
import httl.util.ByteCache;
import httl.util.CharCache;
import httl.util.ClassUtils;
import httl.util.CollectionUtils;
import httl.util.IOUtils;
import httl.util.LinkedStack;
import httl.util.MapEntry;
import httl.util.OrderedMap;
import httl.util.ParameterizedTypeImpl;
import httl.util.Status;
import httl.util.StringCache;
import httl.util.StringSequence;
import httl.util.StringUtils;
import httl.util.VolatileReference;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
/**
* CompileVisitor
*
* @author @author Liang Fei (liangfei0201 AT gmail DOT com)
*/
public class CompiledVisitor extends AstVisitor {
private LinkedStack<Type> typeStack = new LinkedStack<Type>();
private LinkedStack<String> codeStack = new LinkedStack<String>();
private Map<String, Class<?>> variableTypes = new HashMap<String, Class<?>>();
private StringBuilder builder = new StringBuilder();
private StringBuilder textFields = new StringBuilder();
private String filterKey = null;
private VolatileReference<Filter> filterReference = new VolatileReference<Filter>();
private Set<String> setVariables = new HashSet<String>();
private Set<String> getVariables = new HashSet<String>();
private List<String> defVariables = new ArrayList<String>();
private List<Class<?>> defVariableTypes = new ArrayList<Class<?>>();
private Map<String, Class<?>> types = new HashMap<String, Class<?>>();
private Map<String, Class<?>> returnTypes = new HashMap<String, Class<?>>();
private Map<String, Class<?>> macros = new HashMap<String, Class<?>>();
private Resource resource;
private Node node;
private int offset;
private boolean stream;
private String engineName;
private String[] forVariable = new String[] { "for" };
private String[] importGetters = new String[] { "get" };
private String[] importSizers = new String[] { "size", "length" };
private String filterVariable = "filter";
private String formatterVariable = "formatter";
private String defaultFilterVariable;
private String defaultFormatterVariable;
private Switcher<Filter> textFilterSwitcher;
private Switcher<Filter> valueFilterSwitcher;
private Switcher<Formatter<Object>> formatterSwitcher;
private Filter templateFilter;
private Filter textFilter;
private Map<String, Template> importMacroTemplates = new ConcurrentHashMap<String, Template>();
private String[] importPackages;
private Set<String> importPackageSet;
private Map<String, Class<?>> importTypes;
private Map<Class<?>, Object> functions = new ConcurrentHashMap<Class<?>, Object>();
private List<StringSequence> sequences = new CopyOnWriteArrayList<StringSequence>();
private static final String TEMPLATE_CLASS_PREFIX = CompiledTemplate.class.getPackage().getName() + ".Template_";
private final AtomicInteger seq = new AtomicInteger();
private boolean sourceInClass;
private boolean textInClass;
private String outputEncoding;
private Class<?> defaultVariableType;
private Compiler compiler;
public void setCompiler(Compiler compiler) {
this.compiler = compiler;
}
public void setForVariable(String[] forVariable) {
this.forVariable = forVariable;
}
public void setImportSizers(String[] importSizers) {
this.importSizers = importSizers;
}
public void setTypes(Map<String, Class<?>> types) {
this.types = types;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public void setNode(Node node) {
this.node = node;
}
public void setOffset(int offset) {
this.offset = offset;
}
public void setStream(boolean stream) {
this.stream = stream;
}
public void setEngineName(String engineName) {
this.engineName = engineName;
}
public void setFilterVariable(String filterVariable) {
this.filterVariable = filterVariable;
}
public void setFormatterVariable(String formatterVariable) {
this.formatterVariable = formatterVariable;
}
public void setDefaultFilterVariable(String defaultFilterVariable) {
this.defaultFilterVariable = defaultFilterVariable;
}
public void setDefaultFormatterVariable(String defaultFormatterVariable) {
this.defaultFormatterVariable = defaultFormatterVariable;
}
public void setTextFilterSwitcher(Switcher<Filter> textFilterSwitcher) {
this.textFilterSwitcher = textFilterSwitcher;
}
public void setValueFilterSwitcher(Switcher<Filter> valueFilterSwitcher) {
this.valueFilterSwitcher = valueFilterSwitcher;
}
public void setFormatterSwitcher(Switcher<Formatter<Object>> formatterSwitcher) {
this.formatterSwitcher = formatterSwitcher;
}
public void setTemplateFilter(Filter templateFilter) {
this.templateFilter = templateFilter;
}
public void setTextFilter(Filter textFilter) {
this.textFilter = textFilter;
filterReference.set(textFilter);
}
public void setImportMacroTemplates(Map<String, Template> importMacroTemplates) {
this.importMacroTemplates = importMacroTemplates;
}
public void setImportPackages(String[] importPackages) {
this.importPackages = importPackages;
}
public void setImportPackageSet(Set<String> importPackageSet) {
this.importPackageSet = importPackageSet;
}
public void setImportTypes(Map<String, Class<?>> importTypes) {
this.importTypes = importTypes;
}
public void setImportMethods(Map<Class<?>, Object> functions) {
this.functions = functions;
}
public void setImportSequences(List<StringSequence> sequences) {
this.sequences = sequences;
}
public void setImportGetters(String[] importGetters) {
this.importGetters = importGetters;
}
public void setSourceInClass(boolean sourceInClass) {
this.sourceInClass = sourceInClass;
}
public void setTextInClass(boolean textInClass) {
this.textInClass = textInClass;
}
public void setOutputEncoding(String outputEncoding) {
this.outputEncoding = outputEncoding;
}
public void setDefaultVariableType(Class<?> defaultVariableType) {
this.defaultVariableType = defaultVariableType;
}
public CompiledVisitor() {
}
@Override
public boolean visit(Statement node) throws IOException, ParseException {
boolean result = super.visit(node);
filterKey = node.toString();
return result;
}
@Override
public void visit(Text node) throws IOException, ParseException {
String txt = node.getContent();
Filter filter = filterReference.get();
if (textFilterSwitcher != null || valueFilterSwitcher != null || formatterSwitcher != null) {
Set<String> locations = new HashSet<String>();
List<String> textLocations = textFilterSwitcher == null ? null : textFilterSwitcher.locations();
if (textLocations != null) {
locations.addAll(textLocations);
}
List<String> valueLocations = valueFilterSwitcher == null ? null : valueFilterSwitcher.locations();
if (valueLocations != null) {
locations.addAll(valueLocations);
}
List<String> formatterLocations = formatterSwitcher == null ? null : formatterSwitcher.locations();
if (formatterLocations != null) {
locations.addAll(formatterLocations);
}
if (locations != null && locations.size() > 0) {
Map<Integer, Set<String>> switchesd = new TreeMap<Integer, Set<String>>();
for (String location : locations) {
int i = -1;
while ((i = txt.indexOf(location, i + 1)) >= 0) {
Integer key = Integer.valueOf(i);
Set<String> values = switchesd.get(key);
if (values == null) {
values = new HashSet<String>();
switchesd.put(key, values);
}
values.add(location);
}
}
if (switchesd.size() > 0) {
getVariables.add(filterVariable);
int begin = 0;
for (Map.Entry<Integer, Set<String>> entry : switchesd.entrySet()) {
int end = entry.getKey();
String part = getTextPart(txt.substring(begin, end), filter, false);
if (StringUtils.isNotEmpty(part)) {
builder.append(" $output.write(" + part + ");\n");
}
begin = end;
for (String location : entry.getValue()) {
if (textLocations != null && textLocations.contains(location)) {
filter = textFilterSwitcher.switchover(location, textFilter);
filterReference.set(filter);
}
if (valueLocations != null && valueLocations.contains(location)) {
builder.append(" " + filterVariable + " = switchFilter(\"" + StringUtils.escapeString(location) + "\", " + defaultFilterVariable + ");\n");
}
if (formatterLocations != null && formatterLocations.contains(location)) {
builder.append(" " + formatterVariable + " = switchFormatter(\"" + StringUtils.escapeString(location) + "\", " + defaultFormatterVariable + ");\n");
}
}
}
if (begin > 0) {
txt = txt.substring(begin);
}
}
}
}
String part = getTextPart(txt, filter, false);
if (StringUtils.isNotEmpty(part)) {
builder.append(" $output.write(" + part + ");\n");
}
}
@Override
public void visit(ValueDirective node) throws IOException, ParseException {
boolean nofilter = node.isNoFilter();
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
getVariables.addAll(variableTypes.keySet());
if (Template.class.isAssignableFrom(returnType)) {
if (! StringUtils.isNamed(code)) {
code = "(" + code + ")";
}
builder.append(" if (");
builder.append(code);
builder.append(" != null) ");
builder.append(code);
builder.append(".render($output);\n");
} else if (nofilter && Resource.class.isAssignableFrom(returnType)) {
if (! StringUtils.isNamed(code)) {
code = "(" + code + ")";
}
builder.append(" ");
builder.append(IOUtils.class.getName());
builder.append(".copy(");
builder.append(code);
if (stream) {
builder.append(".openStream()");
} else {
builder.append(".openReader()");
}
builder.append(", $output);\n");
} else {
if (Object.class.equals(returnType)) {
if (! StringUtils.isNamed(code)) {
code = "(" + code + ")";
}
builder.append(" if (");
builder.append(code);
builder.append(" instanceof ");
builder.append(Template.class.getName());
builder.append(") {\n ((");
builder.append(Template.class.getName());
builder.append(")");
builder.append(code);
builder.append(").render($output);\n }");
if (nofilter) {
builder.append(" else if (");
builder.append(code);
builder.append(" instanceof ");
builder.append(Resource.class.getName());
builder.append(") {\n ");
builder.append(IOUtils.class.getName());
builder.append(".copy(((");
builder.append(Resource.class.getName());
builder.append(")");
builder.append(code);
if (stream) {
builder.append(").openStream()");
} else {
builder.append(").openReader()");
}
builder.append(", $output);\n }");
} else {
code = "(" + code + " instanceof " + Resource.class.getName() + " ? "
+ IOUtils.class.getName() + ".readToString(((" + Resource.class.getName() + ")"
+ code + ").openReader()) : " + code + ")";
}
builder.append(" else {\n");
} else if (Resource.class.isAssignableFrom(returnType)) {
if (! StringUtils.isNamed(code)) {
code = "(" + code + ")";
}
code = "(" + code + " == null ? null : " + IOUtils.class.getName() + ".readToString(" + code + ".openReader()))";
}
getVariables.add(formatterVariable);
String key = getTextPart(node.getExpression().toString(), null, true);
if (! stream && Object.class.equals(returnType)) {
String pre = "";
String var = "$obj" + seq.getAndIncrement();
pre = " Object " + var + " = " + code + ";\n";
String charsCode = "formatter.toChars(" + key + ", (char[]) " + var + ")";
code = "formatter.toString(" + key + ", " + var + ")";
if (! nofilter) {
getVariables.add(filterVariable);
charsCode = "doFilter(" + filterVariable + ", " + key + ", " + charsCode + ")";
code = "doFilter(" + filterVariable + ", " + key + ", " + code + ")";
}
builder.append(pre);
builder.append(" if (" + var + " instanceof char[]) $output.write(");
builder.append(charsCode);
builder.append("); else $output.write(");
builder.append(code);
builder.append(");\n");
} else {
if (stream) {
code = "formatter.toBytes(" + key + ", " + code + ")";
} else if (char[].class.equals(returnType)) {
code = "formatter.toChars(" + key + ", " + code + ")";
} else {
code = "formatter.toString(" + key + ", " + code + ")";
}
if (! nofilter) {
getVariables.add(filterVariable);
code = "doFilter(" + filterVariable + ", " + key + ", " + code + ")";
}
builder.append(" $output.write(");
builder.append(code);
builder.append(");\n");
}
if (Object.class.equals(returnType)) {
builder.append(" }\n");
}
}
}
@Override
public void visit(SetDirective node) throws IOException, ParseException {
Type type = node.getType();
Class<?> clazz = (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType) type).getRawType() : type);
if (node.getExpression() != null) {
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
if (clazz == null) {
clazz = returnType;
}
appendVar(clazz, node.getName(), code, node.isExport(), node.isHide(), node.getType() != null, node.getOffset());
getVariables.addAll(variableTypes.keySet());
} else {
clazz = checkVar(clazz, node.getName(), node.getOffset());
types.put(node.getName(), clazz);
if (type instanceof ParameterizedType) {
Type[] args = ((ParameterizedType) type).getActualTypeArguments();
for (int i = 0; i < args.length; i ++) {
Class<?> arg = (Class<?>) (args[i] instanceof ParameterizedType ? ((ParameterizedType) args[i]).getRawType() : args[i]);
types.put(node.getName() + ":" + i, arg);
}
}
defVariables.add(node.getName());
defVariableTypes.add(clazz);
}
}
private Class<?> checkVar(Class<?> clazz, String var, int offset) throws IOException, ParseException {
Class<?> cls = types.get(var);
if (cls != null && ! cls.equals(clazz)
&& ! cls.isAssignableFrom(clazz)
&& ! clazz.isAssignableFrom(cls)) {
throw new ParseException("Defined different type variable "
+ var + ", conflict types: " + cls.getCanonicalName() + ", " + clazz.getCanonicalName() + ".", offset);
}
if (cls != null && clazz.isAssignableFrom(cls)) {
return cls;
}
return clazz;
}
private void appendVar(Class<?> clazz, String var, String code, boolean parent, boolean hide, boolean def, int offset) throws IOException, ParseException {
clazz = checkVar(clazz, var, offset);
String type = clazz.getCanonicalName();
if (def || types.get(var) == null) {
types.put(var, clazz);
}
setVariables.add(var);
builder.append(" " + var + " = (" + type + ")(" + code + ");\n");
String ctx = null;
if (parent) {
ctx = "($context.getParent() != null ? $context.getParent() : $context)";
returnTypes.put(var, clazz);
} else if (! hide) {
ctx = "$context";
}
if (StringUtils.isNotEmpty(ctx)) {
builder.append(" " + ctx + ".put(\"");
builder.append(var);
builder.append("\", ");
builder.append(ClassUtils.class.getName() + ".boxed(" + var + ")");
builder.append(");\n");
}
}
@Override
public boolean visit(IfDirective node) throws IOException, ParseException {
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
builder.append(" if(");
builder.append(StringUtils.getConditionCode(returnType, code, importSizers));
builder.append(") {\n");
getVariables.addAll(variableTypes.keySet());
return true;
}
@Override
public void end(IfDirective node) throws IOException, ParseException {
builder.append(" }\n");
}
@Override
public boolean visit(ElseDirective node) throws IOException, ParseException {
if (node.getExpression() == null) {
builder.append(" else {\n");
} else {
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();builder.append(" else if (");
builder.append(StringUtils.getConditionCode(returnType, code, importSizers));
builder.append(") {\n");
getVariables.addAll(variableTypes.keySet());
}
return true;
}
@Override
public void end(ElseDirective node) throws IOException, ParseException {
builder.append(" }\n");
}
@Override
public boolean visit(ForDirective node) throws IOException, ParseException {
String var = node.getName();
Type type = node.getType();
Class<?> clazz = (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType) type).getRawType() : type);
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
String exprName = getGenericVariableName(node.getExpression());
if (clazz == null) {
if (returnType.isArray()) {
clazz = returnType.getComponentType();
} else if (Map.class.isAssignableFrom(returnType)) {
clazz = Map.Entry.class;
} else if (Collection.class.isAssignableFrom(returnType)) {
clazz = types.get(exprName + ":0"); // Collection<T>泛型
if (clazz == null) {
clazz = defaultVariableType;
}
} else {
clazz = defaultVariableType;
}
}
if (Map.class.isAssignableFrom(returnType)) {
Class<?> keyType = types.get(exprName + ":0");
if (keyType != null) {
types.put(var + ":0", keyType);
}
Class<?> valueType = types.get(exprName + ":1");
if (valueType != null) {
types.put(var + ":1", valueType);
}
code = ClassUtils.class.getName() + ".entrySet(" + code + ")";
}
int i = seq.incrementAndGet();
String dataName = "_d_" + i;
String sizeName = "_s_" + i;
String name = "_i_" + var;
builder.append(" " + Object.class.getSimpleName() + " " + dataName + " = " + code + ";\n");
builder.append(" int " + sizeName + " = " + ClassUtils.class.getName() + ".getSize(" + dataName + ");\n");
builder.append(" if (" + dataName + " != null && " + sizeName + " != 0) {\n");
builder.append(" ");
for (String fv : forVariable) {
builder.append(ClassUtils.filterJavaKeyword(fv));
builder.append(" = ");
}
builder.append("new " + Status.class.getName() + "(" + ClassUtils.filterJavaKeyword(forVariable[0]) + ", " + dataName + ", " + sizeName + ");\n");
builder.append(" for (" + Iterator.class.getName() + " " + name + " = " + CollectionUtils.class.getName() + ".toIterator(" + dataName + "); " + name + ".hasNext();) {\n");
String varCode;
if (clazz.isPrimitive()) {
varCode = ClassUtils.class.getName() + ".unboxed((" + ClassUtils.getBoxedClass(clazz).getSimpleName() + ")" + name + ".next())";
} else {
varCode = name + ".next()";
}
appendVar(clazz, var, varCode, false, false, node.getType() != null, node.getOffset());
getVariables.addAll(variableTypes.keySet());
for (String fv : forVariable) {
setVariables.add(fv);
}
return true;
}
@Override
public void end(ForDirective node) throws IOException, ParseException {
builder.append(" " + ClassUtils.filterJavaKeyword(forVariable[0]) + ".increment();\n }\n ");
for (String fv : forVariable) {
builder.append(ClassUtils.filterJavaKeyword(fv));
builder.append(" = ");
}
builder.append(ClassUtils.filterJavaKeyword(forVariable[0]) + ".getParent();\n }\n");
}
@Override
public void visit(BreakDirective node) throws IOException, ParseException {
String b = node.getParent() instanceof ForDirective ? "break" : "return";
if (node.getExpression() == null) {
if (! (node.getParent() instanceof IfDirective
|| node.getParent() instanceof ElseDirective)) {
throw new ParseException("Can not #break without condition. Please use #break(condition) or #if(condition) #break #end.", node.getOffset());
}
builder.append(" " + b + ";\n");
} else {
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
builder.append(" if(");
builder.append(StringUtils.getConditionCode(returnType, code, importSizers));
builder.append(") " + b + ";\n");
getVariables.addAll(variableTypes.keySet());
}
}
@Override
public boolean visit(MacroDirective node) throws IOException, ParseException {
types.put(node.getName(), Template.class);
CompiledVisitor visitor = new CompiledVisitor();
visitor.setResource(resource);
visitor.setNode(node);
visitor.setStream(stream);
visitor.setOffset(offset);
visitor.setDefaultFilterVariable(defaultFilterVariable);
visitor.setDefaultFormatterVariable(defaultFormatterVariable);
visitor.setDefaultVariableType(defaultVariableType);
visitor.setEngineName(engineName);
visitor.setFilterVariable(filterVariable);
visitor.setFormatterSwitcher(formatterSwitcher);
visitor.setFormatterVariable(formatterVariable);
visitor.setForVariable(forVariable);
visitor.setImportMacroTemplates(importMacroTemplates);
visitor.setImportPackages(importPackages);
visitor.setImportPackageSet(importPackageSet);
visitor.setImportSizers(importSizers);
visitor.setImportGetters(importGetters);
visitor.setImportTypes(importTypes);
visitor.setImportMethods(functions);
visitor.setOutputEncoding(outputEncoding);
visitor.setSourceInClass(sourceInClass);
visitor.setTemplateFilter(templateFilter);
visitor.setTextFilter(textFilter);
visitor.setTextFilterSwitcher(textFilterSwitcher);
visitor.setTextInClass(textInClass);
visitor.setValueFilterSwitcher(valueFilterSwitcher);
visitor.setCompiler(compiler);
visitor.init();
for (Node n : node.getChildren()) {
n.accept(visitor);
}
Class<?> macroType = visitor.compile();
macros.put(node.getName(), macroType);
return false;
}
public void init() {
if (types == null) {
types = new HashMap<String, Class<?>>();
}
if (importTypes != null && importTypes.size() > 0) {
types.putAll(importTypes);
}
types.put("this", Template.class);
types.put("super", Template.class);
types.put(defaultFilterVariable, Filter.class);
types.put(filterVariable, Filter.class);
types.put(defaultFormatterVariable, Formatter.class);
types.put(formatterVariable, Formatter.class);
for (String fv : forVariable) {
types.put(fv, Status.class);
}
for (String macro : importMacroTemplates.keySet()) {
types.put(macro, Template.class);
}
}
public Class<?> compile() throws IOException, ParseException {
String code = getCode();
return compiler.compile(code);
}
private String getCode() throws IOException, ParseException {
String name = getTemplateClassName(resource, node, stream);
String code = builder.toString();
int i = name.lastIndexOf('.');
String packageName = i < 0 ? "" : name.substring(0, i);
String className = i < 0 ? name : name.substring(i + 1);
StringBuilder imports = new StringBuilder();
String[] packages = importPackages;
if (packages != null && packages.length > 0) {
for (String pkg : packages) {
imports.append("import ");
imports.append(pkg);
imports.append(".*;\n");
}
}
Set<String> defined = new HashSet<String>();
StringBuilder statusInit = new StringBuilder();
StringBuilder macroFields = new StringBuilder();
StringBuilder macroInits = new StringBuilder();
StringBuilder declare = new StringBuilder();
if (getVariables.contains("this")) {
defined.add("this");
declare.append(" " + Template.class.getName() + " " + ClassUtils.filterJavaKeyword("this") + " = this;\n");
}
if (getVariables.contains("super")) {
defined.add("super");
declare.append(" " + Template.class.getName() + " " + ClassUtils.filterJavaKeyword("super") + " = ($context.getParent() == null ? null : $context.getParent().getTemplate());\n");
}
if (getVariables.contains(filterVariable)) {
defined.add(filterVariable);
defined.add(defaultFilterVariable);
declare.append(" " + Filter.class.getName() + " " + defaultFilterVariable + " = getFilter($context, \"" + filterVariable + "\");\n");
declare.append(" " + Filter.class.getName() + " " + filterVariable + " = " + defaultFilterVariable + ";\n");
}
if (getVariables.contains(formatterVariable)) {
defined.add(formatterVariable);
defined.add(defaultFormatterVariable);
declare.append(" " + MultiFormatter.class.getName() + " " + defaultFormatterVariable + " = getFormatter($context, \"" + formatterVariable + "\");\n");
declare.append(" " + MultiFormatter.class.getName() + " " + formatterVariable + " = " + defaultFormatterVariable + ";\n");
}
for (String var : defVariables) {
if (getVariables.contains(var) && ! defined.contains(var)) {
defined.add(var);
declare.append(getTypeCode(types.get(var), var));
}
}
Set<String> macroKeySet = macros.keySet();
for (String macro : macroKeySet) {
types.put(macro, Template.class);
if (getVariables.contains(macro) && ! defined.contains(macro)) {
defined.add(macro);
macroFields.append("private final " + Template.class.getName() + " " + macro + ";\n");
macroInits.append(" " + macro + " = getMacros().get(\"" + macro + "\");\n");
declare.append(" " + Template.class.getName() + " " + macro + " = getMacro($context, \"" + macro + "\", this." + macro + ");\n");
}
}
if (importTypes != null && importTypes.size() > 0) {
for (Map.Entry<String, Class<?>> entry : importTypes.entrySet()) {
String var = entry.getKey();
if (getVariables.contains(var) && ! defined.contains(var)) {
defined.add(var);
declare.append(getTypeCode(entry.getValue(), var));
}
}
}
for (String macro : importMacroTemplates.keySet()) {
if (getVariables.contains(macro) && ! defined.contains(macro)) {
defined.add(macro);
macroFields.append("private final " + Template.class.getName() + " " + macro + ";\n");
macroInits.append(" " + macro + " = getImportMacros().get(\"" + macro + "\");\n");
declare.append(" " + Template.class.getName() + " " + macro + " = getMacro($context, \"" + macro + "\", this." + macro + ");\n");
}
}
for (String var : setVariables) {
if (! defined.contains(var)) {
defined.add(var);
Class<?> type = types.get(var);
String typeName = getTypeName(type);
declare.append(" " + typeName + " " + ClassUtils.filterJavaKeyword(var) + " = " + ClassUtils.getInitCode(type) + ";\n");
}
}
for (String var : getVariables) {
if (! defined.contains(var)) {
Class<?> type = types.get(var);
if (type == null) {
type = defaultVariableType;
}
defined.add(var);
declare.append(getTypeCode(type, var));
defVariables.add(var);
defVariableTypes.add(type);
}
}
StringBuilder funtionFileds = new StringBuilder();
StringBuilder functionInits = new StringBuilder();
for (Map.Entry<Class<?>, Object> function : functions.entrySet()) {
Class<?> functionType = function.getKey();
if (function.getValue() instanceof Class) {
continue;
}
String pkgName = functionType.getPackage() == null ? null : functionType.getPackage().getName();
String typeName;
if (pkgName != null && ("java.lang".equals(pkgName)
|| (importPackageSet != null && importPackageSet.contains(pkgName)))) {
typeName = functionType.getSimpleName();
} else {
typeName = functionType.getCanonicalName();
}
funtionFileds.append("private final ");
funtionFileds.append(typeName);
funtionFileds.append(" $");
funtionFileds.append(functionType.getName().replace('.','_'));
funtionFileds.append(";\n");
functionInits.append(" this.$");
functionInits.append(functionType.getName().replace('.','_'));
functionInits.append(" = (");
functionInits.append(typeName);
functionInits.append(") functions.get(");
functionInits.append(typeName);
functionInits.append(".class);\n");
}
String methodCode = statusInit.toString() + declare + code;
textFields.append("private static final " + Map.class.getName() + " $VARS = " + toTypeCode(defVariables, defVariableTypes) + ";\n");
String templateName = resource.getName();
Node macro = node;
while (macro instanceof MacroDirective) {
templateName += "#" + ((MacroDirective) macro).getName();
macro = ((MacroDirective) macro).getParent();
}
String sorceCode = "package " + packageName + ";\n"
+ "\n"
+ imports.toString()
+ "\n"
+ "public final class " + className + " extends " + (stream ? OutputStreamTemplate.class.getName() : WriterTemplate.class.getName()) + " {\n"
+ "\n"
+ textFields
+ "\n"
+ funtionFileds
+ "\n"
+ macroFields
+ "\n"
+ "public " + className + "("
+ Engine.class.getName() + " engine, "
+ Interceptor.class.getName() + " interceptor, "
+ Compiler.class.getName() + " compiler, "
+ Switcher.class.getName() + " filterSwitcher, "
+ Switcher.class.getName() + " formatterSwitcher, "
+ Filter.class.getName() + " filter, "
+ Formatter.class.getName() + " formatter, "
+ Converter.class.getName() + " mapConverter, "
+ Converter.class.getName() + " outConverter, "
+ Map.class.getName() + " functions, "
+ Map.class.getName() + " importMacros, "
+ Resource.class.getName() + " resource, "
+ Template.class.getName() + " parent, "
+ Node.class.getName() + " root) {\n"
+ " super(engine, interceptor, compiler, filterSwitcher, formatterSwitcher, filter, formatter, mapConverter, outConverter, functions, importMacros, resource, parent, root);\n"
+ functionInits
+ macroInits
+ "}\n"
+ "\n"
+ "protected void doRender(" + Context.class.getName() + " $context, "
+ (stream ? OutputStream.class.getName() : Writer.class.getName())
+ " $output) throws " + Exception.class.getName() + " {\n"
+ methodCode
+ "}\n"
+ "\n"
+ "public " + String.class.getSimpleName() + " getName() {\n"
+ " return \"" + templateName + "\";\n"
+ "}\n"
+ "\n"
+ "public " + Map.class.getName() + " getVariables() {\n"
+ " return $VARS;\n"
+ "}\n"
+ "\n"
+ "protected " + Map.class.getName() + " getMacroTypes() {\n"
+ " return " + toTypeCode(macros) + ";\n"
+ "}\n"
+ "\n"
+ "public boolean isMacro() {\n"
+ " return " + (node instanceof MacroDirective) + ";\n"
+ "}\n"
+ "\n"
+ "public int getOffset() {\n"
+ " return " + offset + ";\n"
+ "}\n"
+ "\n"
+ "}\n";
return sorceCode;
}
private String getTypeName(Class<?> type) {
return type.getCanonicalName();
}
private String getTypeCode(Class<?> type, String var) {
String typeName = getTypeName(type);
if (type.isPrimitive()) {
return " " + typeName + " " + ClassUtils.filterJavaKeyword(var) + " = " + ClassUtils.class.getName() + ".unboxed((" + ClassUtils.getBoxedClass(type).getSimpleName() + ") $context.get(\"" + var + "\"));\n";
} else {
return " " + typeName + " " + ClassUtils.filterJavaKeyword(var) + " = (" + typeName + ") $context.get(\"" + var + "\");\n";
}
}
private String toTypeCode(Map<String, Class<?>> types) {
StringBuilder keyBuf = new StringBuilder();
StringBuilder valueBuf = new StringBuilder();
if (types == null || types.size() == 0) {
keyBuf.append("new String[0]");
valueBuf.append("new Class[0]");
} else {
keyBuf.append("new String[] {");
valueBuf.append("new Class[] {");
boolean first = true;
for (Map.Entry<String, Class<?>> entry : types.entrySet()) {
if (first) {
first = false;
} else {
keyBuf.append(", ");
valueBuf.append(", ");
}
keyBuf.append("\"");
keyBuf.append(StringUtils.escapeString(entry.getKey()));
keyBuf.append("\"");
valueBuf.append(entry.getValue().getCanonicalName());
valueBuf.append(".class");;
}
keyBuf.append("}");
valueBuf.append("}");
}
StringBuilder buf = new StringBuilder();
buf.append("new ");
buf.append(OrderedMap.class.getName());
buf.append("(");
buf.append(keyBuf);
buf.append(", ");
buf.append(valueBuf);
buf.append(")");
return buf.toString();
}
private String toTypeCode(List<String> names, List<Class<?>> types) {
StringBuilder buf = new StringBuilder();
buf.append("new ");
buf.append(OrderedMap.class.getName());
buf.append("(");
if (names == null || names.size() == 0) {
buf.append("new String[0]");
} else {
buf.append("new String[] {");
boolean first = true;
for (String str : names) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append("\"");
buf.append(StringUtils.escapeString(str));
buf.append("\"");
}
buf.append("}");
}
buf.append(", ");
if (names == null || names.size() == 0) {
buf.append("new Class[0]");
} else {
buf.append("new Class[] {");
boolean first = true;
for (Class<?> cls : types) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(cls.getCanonicalName());
buf.append(".class");
}
buf.append("}");
}
buf.append(")");
return buf.toString();
}
private String getTemplateClassName(Resource resource, Node node, boolean stream) {
String name = resource.getName();
String encoding = resource.getEncoding();
Locale locale = resource.getLocale();
long lastModified = resource.getLastModified();
StringBuilder buf = new StringBuilder(name.length() + 40);
buf.append(name);
Node macro = node;
while (macro instanceof MacroDirective) {
buf.append("_");
buf.append(((MacroDirective) macro).getName());
macro = ((MacroDirective) macro).getParent();
}
if (StringUtils.isNotEmpty(engineName)) {
buf.append("_");
buf.append(engineName);
}
if (StringUtils.isNotEmpty(encoding)) {
buf.append("_");
buf.append(encoding);
}
if (locale != null) {
buf.append("_");
buf.append(locale);
}
if (lastModified > 0) {
buf.append("_");
buf.append(lastModified);
}
buf.append(stream ? "_stream" : "_writer");
return TEMPLATE_CLASS_PREFIX + StringUtils.getVaildName(buf.toString());
}
private String getTextPart(String txt, Filter filter, boolean string) {
if (StringUtils.isNotEmpty(txt)) {
if (filter != null) {
txt = filter.filter(filterKey, txt);
}
String var = "$TXT" + seq.incrementAndGet();
if (string) {
if (textInClass) {
textFields.append("private static final String " + var + " = \"" + StringUtils.escapeString(txt) + "\";\n");
} else {
String txtId = StringCache.put(txt);
textFields.append("private static final String " + var + " = " + StringCache.class.getName() + ".getAndRemove(\"" + txtId + "\");\n");
}
} else if (stream) {
if (textInClass) {
textFields.append("private static final byte[] " + var + " = new byte[] {" + StringUtils.toByteString(StringUtils.toBytes(txt, outputEncoding)) + "};\n");
} else {
String txtId = ByteCache.put(StringUtils.toBytes(txt, outputEncoding));
textFields.append("private static final byte[] " + var + " = " + ByteCache.class.getName() + ".getAndRemove(\"" + txtId + "\");\n");
}
} else {
if (textInClass) {
textFields.append("private static final char[] " + var + " = new char[] {" + StringUtils.toCharString(txt.toCharArray()) + "};\n");
} else {
String txtId = CharCache.put(txt.toCharArray());
textFields.append("private static final char[] " + var + " = " + CharCache.class.getName() + ".getAndRemove(\"" + txtId + "\");\n");
}
}
return var;
}
return "";
}
private String popExpressionCode() {
String code = codeStack.pop();
if (! codeStack.isEmpty()) {
throw new IllegalStateException("Illegal expression.");
}
return code;
}
private Class<?> popExpressionReturnType() {
Type type = typeStack.pop();
if (! typeStack.isEmpty()) {
throw new IllegalStateException("Illegal expression.");
}
return (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType)type).getRawType() : type);
}
private Map<String, Class<?>> popExpressionVariableTypes() {
Map<String, Class<?>> types = variableTypes;
variableTypes = new HashMap<String, Class<?>>();
return types;
}
public void visit(Constant node) throws IOException, ParseException {
Object value = node.getValue();
Class<?> type;
String code;
if (value == null) {
type = node.isBoxed() ? void.class : null;
code = node.isBoxed() ? "" : "null";
} else if (value.equals(Boolean.TRUE)) {
type = node.isBoxed() ? Boolean.class : boolean.class;
code = node.isBoxed() ? "Boolean.TRUE" : "true";
} else if (value.equals(Boolean.FALSE)) {
type = node.isBoxed() ? Boolean.class : boolean.class;
code = node.isBoxed() ? "Boolean.FALSE" : "false";
} else if (value instanceof String) {
type = String.class;
code = "\"" + StringUtils.escapeString((String) value) + "\"";
} else if (value instanceof Character) {
type = node.isBoxed() ? Character.class : char.class;
code = node.isBoxed() ? "Character.valueOf('" + StringUtils.escapeString(String.valueOf(value)) + "')"
: "'" + StringUtils.escapeString(String.valueOf(value)) + "'";
} else if (value instanceof Double) {
type = node.isBoxed() ? Double.class : double.class;
code = node.isBoxed() ? "Double.valueOf(" + value + "d)" : value + "d";
} else if (value instanceof Float) {
type = node.isBoxed() ? Float.class : float.class;
code = node.isBoxed() ? "Float.valueOf(" + value + "f)" : value + "f";
} else if (value instanceof Long) {
type = node.isBoxed() ? Long.class : long.class;
code = node.isBoxed() ? "Long.valueOf(" + value + "l)" : value + "l";
} else if (value instanceof Short) {
type = node.isBoxed() ? Short.class : short.class;
code = node.isBoxed() ? "Short.valueOf((short)" + value + ")" : "((short)" + value + ")";
} else if (value instanceof Byte) {
type = node.isBoxed() ? Byte.class : byte.class;
code = node.isBoxed() ? "Byte.valueOf((byte)" + value + ")" : "((byte)" + value + ")";
} else if (value instanceof Integer) {
type = node.isBoxed() ? Integer.class : int.class;
code = node.isBoxed() ? "Integer.valueOf(" + value + ")" : String.valueOf(value);
} else if (value instanceof Class) {
type = node.isBoxed() ? ClassUtils.getBoxedClass((Class<?>) value) : (Class<?>) value;
code = ((Class<?>) value).getCanonicalName();
} else {
throw new ParseException("Unsupported constant " + value, node.getOffset());
}
typeStack.push(type);
codeStack.push(code);
}
public void visit(Variable node) throws IOException, ParseException {
String name = node.getName();
Class<?> type = types.get(name);
if (type == null) {
type = defaultVariableType;
if (type == null) {
type = Object.class;
}
}
String code = ClassUtils.filterJavaKeyword(name);
typeStack.push(type);
codeStack.push(code);
variableTypes.put(name, type);
}
@Override
public void visit(PositiveOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Type type = parameterType;
String code = parameterCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(NegativeOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
String name = node.getName();
Type type = parameterClass;
String code;
if (node.getParameter() instanceof Operator
&& ((Operator) node.getParameter()).getPriority() < node.getPriority()) {
code = name + " (" + parameterCode + ")";
} else {
code = name + " " + parameterCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(NotOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
Type type = boolean.class;
String code = "! (" + StringUtils.getConditionCode(parameterClass, parameterCode, importSizers) + ")";
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(BitNotOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
String name = node.getName();
Type type = parameterClass;
String code;
if (node.getParameter() instanceof Operator
&& ((Operator) node.getParameter()).getPriority() < node.getPriority()) {
code = name + " (" + parameterCode + ")";
} else {
code = name + " " + parameterCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(ListOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
Type type = null;
String code = null;
if (parameterType instanceof ParameterizedType) {
parameterClass = (Class<?>)((ParameterizedType) parameterType).getActualTypeArguments()[0];
}
if (Map.Entry.class.isAssignableFrom(parameterClass)) {
type = Map.class;
code = CollectionUtils.class.getName() + ".toMap(new " + Map.Entry.class.getCanonicalName() + "[] {" + parameterCode + "})";
} else {
type = Array.newInstance(parameterClass, 0).getClass();
code = "new " + parameterClass.getCanonicalName() + "[] {" + parameterCode + "}";
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(NewOperator node) throws IOException, ParseException {
typeStack.pop();
String parameterCode = codeStack.pop();
String name = node.getName();
Type type = ClassUtils.forName(importPackages, name);
String code = "new " + name + "(" + parameterCode + ")";
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(StaticMethodOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
String name = node.getName();
Type type = null;
String code = null;
Class<?>[] parameterTypes;
if (parameterType instanceof ParameterizedType) {
parameterTypes = (Class<?>[]) ((ParameterizedType) parameterType).getActualTypeArguments();
} else if (parameterClass == void.class) {
parameterTypes = new Class<?>[0];
} else {
parameterTypes = new Class<?>[] { parameterClass };
}
Class<?> t = types.get(name);
if (t != null && Template.class.isAssignableFrom(t)) {
variableTypes.put(name, Template.class);
type = Object.class;
code = "(" + name + " == null ? null : " + name + ".evaluate(new Object" + (parameterCode.length() == 0 ? "[0]" : "[] { " + parameterCode + " }") + "))";
} else {
name = ClassUtils.filterJavaKeyword(name);
type = null;
code = null;
if (functions != null && functions.size() > 0) {
for (Class<?> function : functions.keySet()) {
try {
Method method = ClassUtils.searchMethod(function, name, parameterTypes);
if (Object.class.equals(method.getDeclaringClass())) {
break;
}
type = method.getReturnType();
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + function.getName(), node.getOffset());
}
if (Modifier.isStatic(method.getModifiers())) {
code = function.getName() + "." + method.getName() + "(" + parameterCode + ")";
} else {
code = "$" + function.getName().replace('.', '_') + "." + method.getName() + "(" + parameterCode + ")";
}
break;
} catch (NoSuchMethodException e) {
}
}
}
if (code == null) {
throw new ParseException("No such macro \"" + name + "\" or import method " + ClassUtils.getMethodFullName(name, parameterTypes) + ".", node.getOffset());
}
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(CastOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
String name = node.getName();
Type type = ClassUtils.forName(importPackages, name);
String code = parameterCode;
if (! type.equals(parameterType)) {
code = "(" + name + ")(" + parameterCode + ")";
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(AddOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if ((Collection.class.isAssignableFrom(leftClass) || leftClass.isArray())
&& (Collection.class.isAssignableFrom(rightClass) || rightClass.isArray())
|| Map.class.isAssignableFrom(leftClass) && Map.class.isAssignableFrom(rightClass)) {
code = CollectionUtils.class.getName() + ".merge(" + leftCode+ ", " + rightCode + ")";
type = leftType;
} else if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = String.class;
}
if (type != String.class) {
Class<?> clazz = (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType)type).getRawType() : type);
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(SubOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type;
if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = int.class;
}
Class<?> clazz = (Class<?>) type;
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(MulOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type;
if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = int.class;
}
Class<?> clazz = (Class<?>) type;
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(DivOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type;
if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = int.class;
}
Class<?> clazz = (Class<?>) type;
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(ModOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type;
if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = int.class;
}
Class<?> clazz = (Class<?>) type;
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(EqualsOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code;
if(! "null".equals(leftCode) && ! "null".equals(rightCode)
&& ! leftClass.isPrimitive() && ! rightClass.isPrimitive()) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".equals(" + rightCode + ")");
} else {
code = leftCode + " == " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(NotEqualsOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code;
if(! "null".equals(leftCode) && ! "null".equals(rightCode)
&& ! leftClass.isPrimitive() && ! rightClass.isPrimitive()) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "(! " + leftCode + ".equals(" + rightCode + "))");
} else {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(GreaterOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = null;
if (leftClass != null && Comparable.class.isAssignableFrom(leftClass)) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".compareTo(" + rightCode + ") > 0");
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(GreaterEqualsOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = null;
if (leftClass != null && Comparable.class.isAssignableFrom(leftClass)) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".compareTo(" + rightCode + ") >= 0");
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(LessOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = null;
if (leftClass != null && Comparable.class.isAssignableFrom(leftClass)) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".compareTo(" + rightCode + ") < 0");
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(LessEqualsOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = null;
if (leftClass != null && Comparable.class.isAssignableFrom(leftClass)) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".compareTo(" + rightCode + ") <= 0");
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(AndOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
if(! boolean.class.equals(leftClass)) {
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
leftCode = StringUtils.getConditionCode(leftClass, leftCode, importSizers);
rightCode = StringUtils.getConditionCode(rightClass, rightCode, importSizers);
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(OrOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftClass;
String code = null;
if(! boolean.class.equals(leftClass)) {
code = "(" + StringUtils.getConditionCode(leftClass, leftCode, importSizers) + " ? (" + leftCode + ") : (" + rightCode + "))";
} else {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(BitAndOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(BitOrOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(BitXorOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(RightShiftOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(LeftShiftOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(UnsignShiftOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(ArrayOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
List<Class<?>> ts = new ArrayList<Class<?>>();
if (leftType instanceof ParameterizedType) {
for (Type t : ((ParameterizedType) leftType).getActualTypeArguments()) {
ts.add((Class<?>) t);
}
} else if (leftType != void.class) {
ts.add((Class<?>) leftType);
}
if (rightType instanceof ParameterizedType) {
for (Type t : ((ParameterizedType) rightType).getActualTypeArguments()) {
ts.add((Class<?>) t);
}
} else if (rightType != void.class) {
ts.add((Class<?>) rightType);
}
type = new ParameterizedTypeImpl(Object[].class, ts.toArray(new Class<?>[ts.size()]));
code = leftCode + ", " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(ConditionOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = rightClass;
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
leftCode = StringUtils.getConditionCode(leftClass, leftCode, importSizers);
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(EntryOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if(! (node.getLeftParameter() instanceof BinaryOperator
&& "?".equals(((BinaryOperator)node.getLeftParameter()).getName()))) {
type = Map.Entry.class;
code = "new " + MapEntry.class.getName() + "(" + leftCode + ", " + rightCode + ")";
} else {
type = leftType;
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(InstanceofOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(IndexOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if (Map.class.isAssignableFrom(leftClass)) {
String var = getGenericVariableName(node.getLeftParameter());
if (var != null && types.containsKey(var + ":1")) {
Class<?> varType = types.get(var + ":1"); // Map<K,V>第二个泛型
type = varType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + varType.getCanonicalName() + ")" + leftCode + ".get(" + rightCode + "))");
} else {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".get(" + rightCode + ")");
}
} else if (List.class.isAssignableFrom(leftClass)) {
if (int[].class == rightType) {
type = List.class;;
code = CollectionUtils.class.getName() + ".subList(" + leftCode + ", " + rightCode + ")";
} else if (rightType instanceof ParameterizedType
&& ((ParameterizedType) rightType).getActualTypeArguments()[0] == int.class) {
type = List.class;;
code = CollectionUtils.class.getName() + ".subList(" + leftCode + ", new int[] {" + rightCode + "})";
} else if (int.class.equals(rightType)) {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".get(" + rightCode + ")");
if (node.getLeftParameter() instanceof Variable) {
String var = ((Variable)node.getLeftParameter()).getName();
Class<?> varType = types.get(var + ":0"); // List<T>第一个泛型
if (varType != null) {
type = varType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + varType.getCanonicalName() + ")" + leftCode + ".get(" + rightCode + "))");
}
}
} else {
throw new ParseException("The \"[]\" index type: " + rightType + " must be int!", node.getOffset());
}
} else if (leftClass.isArray()) {
if (int[].class == rightType) {
type = leftClass;
code = CollectionUtils.class.getName() + ".subArray(" + leftCode + ", " + rightCode + ")";
} else if (rightType instanceof ParameterizedType
&& ((ParameterizedType) rightType).getActualTypeArguments()[0] == int.class) {
type = leftClass;
code = CollectionUtils.class.getName() + ".subArray(" + leftCode + ", new int[] {" + rightCode + "})";
} else if (int.class.equals(rightType)) {
type = leftClass.getComponentType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "[" + rightCode + "]");
} else {
throw new ParseException("The \"[]\" index type: " + rightType + " must be int!", node.getOffset());
}
} else {
throw new ParseException("Unsuptorted \"[]\" for non-array type: " + leftClass, node.getOffset());
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(SequenceOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if (leftClass == int.class || leftClass == Integer.class
|| leftClass == short.class || leftClass == Short.class
|| leftClass == long.class || leftClass == Long.class
|| leftClass == char.class || leftClass == Character.class) {
type = Array.newInstance(leftClass, 0).getClass();
code = CollectionUtils.class.getName() + ".createSequence(" + leftCode + ", " + rightCode + ")";
} else if (leftClass == String.class
&& leftCode.length() >= 2 && rightCode.length() >= 2
&& (leftCode.startsWith("\"") || leftCode.startsWith("\'"))
&& (leftCode.endsWith("\"") || leftCode.endsWith("\'"))
&& (rightCode.startsWith("\"") || rightCode.startsWith("\'"))
&& (rightCode.endsWith("\"") || rightCode.endsWith("\'"))) {
type = String[].class;
StringBuilder buf = new StringBuilder();
for (String s : getSequence(leftCode.substring(1, leftCode.length() - 1),
rightCode.substring(1, rightCode.length() - 1))) {
if (buf.length() > 0) {
buf.append(",");
}
buf.append("\"");
buf.append(s);
buf.append("\"");
}
code = "new String[] {" + buf.toString() + "}";
} else {
throw new ParseException("The operator \"..\" unsupported parameter type " + leftClass, node.getOffset());
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(MethodOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if ("to".equals(name)
&& node.getRightParameter() instanceof Constant
&& rightType == String.class
&& rightCode.length() > 2
&& rightCode.startsWith("\"") && rightCode.endsWith("\"")) {
code = "((" + rightCode.substring(1, rightCode.length() - 1) + ")" + leftCode + ")";
type = ClassUtils.forName(importPackages, rightCode.substring(1, rightCode.length() - 1));
} else if ("class".equals(name)) {
type = Class.class;
if (leftClass.isPrimitive()) {
code = leftClass.getCanonicalName() + ".class";
} else {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".getClass()");
}
} else if (Map.Entry.class.isAssignableFrom(leftClass)
&& ("key".equals(name) || "value".equals(name))) {
String var = getGenericVariableName(node.getLeftParameter());
if (var != null) {
Class<?> keyType = types.get(var + ":0"); // Map<K,V>第一个泛型
Class<?> valueType = types.get(var + ":1"); // Map<K,V>第二个泛型
if ("key".equals(name) && keyType != null) {
type = keyType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + keyType.getCanonicalName() + ")" + leftCode + ".getKey(" + rightCode + "))");
} else if ("value".equals(name) && valueType != null) {
type = valueType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + valueType.getCanonicalName() + ")" + leftCode + ".getValue(" + rightCode + "))");
}
}
} else if (Map.class.isAssignableFrom(leftClass)
&& "get".equals(name)
&& String.class.equals(rightType)) {
String var = getGenericVariableName(node.getLeftParameter());
if (var != null) {
Class<?> varType = types.get(var + ":1"); // Map<K,V>第二个泛型
if (varType != null) {
type = varType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + varType.getCanonicalName() + ")" + leftCode + ".get(" + rightCode + "))");
}
}
} else if (List.class.isAssignableFrom(leftClass)
&& "get".equals(name)
&& int.class.equals(rightType)) {
String var = getGenericVariableName(node.getLeftParameter());
if (var != null) {
Class<?> varType = types.get(var + ":0"); // List<T>第一个泛型
if (varType != null) {
type = varType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + varType.getCanonicalName() + ")" + leftCode + ".get(" + rightCode + "))");
}
}
}
if (code == null) {
Class<?>[] rightTypes;
if (rightType instanceof ParameterizedType) {
rightTypes = (Class<?>[]) ((ParameterizedType) rightType).getActualTypeArguments();
} else if (rightClass == void.class) {
rightTypes = new Class<?>[0];
} else {
rightTypes = new Class<?>[] { rightClass };
}
if (Template.class.isAssignableFrom(leftClass)
&& ! hasMethod(Template.class, name, rightTypes)) {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, CompiledVisitor.class.getName() + ".getMacro(" + leftCode + ", \"" + name + "\").evaluate(new Object" + (rightCode.length() == 0 ? "[0]" : "[] { " + rightCode + " }") + ")");
} else if (Map.class.isAssignableFrom(leftClass)
&& rightTypes.length == 0
&& ! hasMethod(Map.class, name, rightTypes)) {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".get(\"" + name + "\")");
String var = getGenericVariableName(node.getLeftParameter());
if (var != null) {
Class<?> t = types.get(var + ":1"); // Map<K,V>第二个泛型
if (t != null) {
type = t;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + t.getCanonicalName() + ")" + leftCode + ".get(\"" + name + "\"))");
}
}
} else if (importGetters != null && importGetters.length > 0
&& rightTypes.length == 0
&& ! hasMethod(leftClass, name, rightTypes)) {
for (String getter : importGetters) {
if (hasMethod(leftClass, getter, new Class<?>[] { String.class })
|| hasMethod(leftClass, getter, new Class<?>[] { Object.class })) {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + getter + "(\"" + name + "\")");
break;
}
}
}
name = ClassUtils.filterJavaKeyword(name);
if (functions != null && functions.size() > 0) {
Class<?>[] allTypes;
String allCode;
if (rightTypes == null || rightTypes.length == 0) {
allTypes = new Class<?>[] {leftClass};
allCode = leftCode;
} else {
allTypes = new Class<?>[rightTypes.length + 1];
allTypes[0] = leftClass;
System.arraycopy(rightTypes, 0, allTypes, 1, rightTypes.length);
allCode = leftCode + ", " + rightCode;
}
for (Class<?> function : functions.keySet()) {
try {
Method method = ClassUtils.searchMethod(function, name, allTypes);
if (! Object.class.equals(method.getDeclaringClass())) {
type = method.getReturnType();
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + function.getName(), node.getOffset());
}
if (Modifier.isStatic(method.getModifiers())) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, function.getName() + "." + method.getName() + "(" + allCode + ")");
} else {
code = "$" + function.getName().replace('.', '_') + "." + method.getName() + "(" + allCode + ")";
}
break;
}
} catch (NoSuchMethodException e) {
}
}
}
if (code == null) {
if (leftClass.isArray() && "length".equals(name)) {
type = int.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".length");
} else {
try {
Method method = ClassUtils.searchMethod(leftClass, name, rightTypes);
type = method.getReturnType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + method.getName() + "(" + rightCode + ")");
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + leftClass.getName(), node.getOffset());
}
} catch (NoSuchMethodException e) {
String def = "";
if (StringUtils.isNamed(leftCode) && leftClass.equals(defaultVariableType)) {
def = " Please add variable type definition #set(Xxx " + leftCode + ") in your template.";
}
if (rightTypes != null && rightTypes.length > 0) {
throw new ParseException("No such method " + ClassUtils.getMethodFullName(name, rightTypes) + " in class "
+ leftClass.getName() + "." + def, node.getOffset());
} else { // search property
try {
String getter = "get" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method method = leftClass.getMethod(getter,
new Class<?>[0]);
type = method.getReturnType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + method.getName() + "()");
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + leftClass.getName(), node.getOffset());
}
} catch (NoSuchMethodException e2) {
try {
String getter = "is"
+ name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method method = leftClass.getMethod(getter,
new Class<?>[0]);
type = method.getReturnType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + method.getName() + "()");
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + leftClass.getName(), node.getOffset());
}
} catch (NoSuchMethodException e3) {
try {
Field field = leftClass.getField(name);
type = field.getType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + field.getName());
} catch (NoSuchFieldException e4) {
throw new ParseException(
"No such property "
+ name
+ " in class "
+ leftClass.getName()
+ ", because no such method get"
+ name.substring(0, 1)
.toUpperCase()
+ name.substring(1)
+ "() or method is"
+ name.substring(0, 1)
.toUpperCase()
+ name.substring(1)
+ "() or method " + name
+ "() or filed " + name + "." + def, node.getOffset());
}
}
}
}
}
}
}
}
typeStack.push(type);
codeStack.push(code);
}
private static String getGenericVariableName(Expression node) {
if (node instanceof Variable) {
return ((Variable)node).getName();
}
while (node instanceof BinaryOperator) {
String name = ((BinaryOperator)node).getName();
if ("+".equals(name) || "||".equals(name)
|| "&&".equals(name)
|| ".entrySet".equals(name)) {
node = ((BinaryOperator)node).getLeftParameter();
if (node instanceof Variable) {
return ((Variable)node).getName();
}
} else {
return null;
}
}
return null;
}
private List<String> getSequence(String begin, String end) {
if (sequences != null) {
for (StringSequence sequence : sequences) {
if (sequence.containSequence(begin, end)) {
return sequence.getSequence(begin, end);
}
}
}
throw new IllegalStateException("No such sequence from \"" + begin + "\" to \"" + end + "\".");
}
public static Template getMacro(Template template, String name) {
Template macro = template.getMacros().get(name);
if (macro == null) {
throw new IllegalStateException("No such macro " + name + "in template " + template.getName());
}
return macro;
}
private String getNotNullCode(Node leftParameter, Type type, String leftCode, String code) throws IOException, ParseException {
if (leftParameter instanceof Constant) {
return code;
}
Class<?> clazz = (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType)type).getRawType() : type);
return "(" + leftCode + " == null ? (" + clazz.getCanonicalName() + ")" + ClassUtils.getInitCode(clazz) + " : " + code + ")";
}
private boolean hasMethod(Class<?> leftClass, String name, Class<?>[] rightTypes) {
if (leftClass == null) {
return false;
}
if (leftClass.isArray() && "length".equals(name)) {
return true;
}
try {
Method method = ClassUtils.searchMethod(leftClass, name, rightTypes);
return method != null;
} catch (NoSuchMethodException e) {
if (rightTypes != null && rightTypes.length > 0) {
return false;
} else { // search property
try {
String getter = "get" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method method = leftClass.getMethod(getter,
new Class<?>[0]);
return method != null;
} catch (NoSuchMethodException e2) {
try {
String getter = "is"
+ name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method method = leftClass.getMethod(getter,
new Class<?>[0]);
return method != null;
} catch (NoSuchMethodException e3) {
try {
Field field = leftClass.getField(name);
return field != null;
} catch (NoSuchFieldException e4) {
return false;
}
}
}
}
}
}
} | httl/src/main/java/httl/spi/translators/templates/CompiledVisitor.java | /*
* Copyright 2011-2013 HTTL Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package httl.spi.translators.templates;
import httl.Context;
import httl.Engine;
import httl.Node;
import httl.Resource;
import httl.Template;
import httl.ast.AddOperator;
import httl.ast.AndOperator;
import httl.ast.ArrayOperator;
import httl.ast.AstVisitor;
import httl.ast.BinaryOperator;
import httl.ast.BitAndOperator;
import httl.ast.BitNotOperator;
import httl.ast.BitOrOperator;
import httl.ast.BitXorOperator;
import httl.ast.BreakDirective;
import httl.ast.CastOperator;
import httl.ast.ConditionOperator;
import httl.ast.Constant;
import httl.ast.DivOperator;
import httl.ast.ElseDirective;
import httl.ast.EntryOperator;
import httl.ast.EqualsOperator;
import httl.ast.Expression;
import httl.ast.ForDirective;
import httl.ast.GreaterEqualsOperator;
import httl.ast.GreaterOperator;
import httl.ast.IfDirective;
import httl.ast.IndexOperator;
import httl.ast.InstanceofOperator;
import httl.ast.LeftShiftOperator;
import httl.ast.LessEqualsOperator;
import httl.ast.LessOperator;
import httl.ast.ListOperator;
import httl.ast.MacroDirective;
import httl.ast.MethodOperator;
import httl.ast.ModOperator;
import httl.ast.MulOperator;
import httl.ast.NegativeOperator;
import httl.ast.NewOperator;
import httl.ast.NotEqualsOperator;
import httl.ast.NotOperator;
import httl.ast.Operator;
import httl.ast.OrOperator;
import httl.ast.PositiveOperator;
import httl.ast.RightShiftOperator;
import httl.ast.SequenceOperator;
import httl.ast.SetDirective;
import httl.ast.Statement;
import httl.ast.StaticMethodOperator;
import httl.ast.SubOperator;
import httl.ast.Text;
import httl.ast.UnsignShiftOperator;
import httl.ast.ValueDirective;
import httl.ast.Variable;
import httl.spi.Compiler;
import httl.spi.Converter;
import httl.spi.Filter;
import httl.spi.Formatter;
import httl.spi.Interceptor;
import httl.spi.Switcher;
import httl.spi.formatters.MultiFormatter;
import httl.util.ByteCache;
import httl.util.CharCache;
import httl.util.ClassUtils;
import httl.util.CollectionUtils;
import httl.util.IOUtils;
import httl.util.LinkedStack;
import httl.util.MapEntry;
import httl.util.OrderedMap;
import httl.util.ParameterizedTypeImpl;
import httl.util.Status;
import httl.util.StringCache;
import httl.util.StringSequence;
import httl.util.StringUtils;
import httl.util.VolatileReference;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
/**
* CompileVisitor
*
* @author @author Liang Fei (liangfei0201 AT gmail DOT com)
*/
public class CompiledVisitor extends AstVisitor {
private LinkedStack<Type> typeStack = new LinkedStack<Type>();
private LinkedStack<String> codeStack = new LinkedStack<String>();
private Map<String, Class<?>> variableTypes = new HashMap<String, Class<?>>();
private StringBuilder builder = new StringBuilder();
private StringBuilder textFields = new StringBuilder();
private String filterKey = null;
private VolatileReference<Filter> filterReference = new VolatileReference<Filter>();
private Set<String> setVariables = new HashSet<String>();
private Set<String> getVariables = new HashSet<String>();
private List<String> defVariables = new ArrayList<String>();
private List<Class<?>> defVariableTypes = new ArrayList<Class<?>>();
private Map<String, Class<?>> types = new HashMap<String, Class<?>>();
private Map<String, Class<?>> returnTypes = new HashMap<String, Class<?>>();
private Map<String, Class<?>> macros = new HashMap<String, Class<?>>();
private Resource resource;
private Node node;
private int offset;
private boolean stream;
private String engineName;
private String[] forVariable = new String[] { "for" };
private String[] importGetters = new String[] { "get" };
private String[] importSizers = new String[] { "size", "length" };
private String filterVariable = "filter";
private String formatterVariable = "formatter";
private String defaultFilterVariable;
private String defaultFormatterVariable;
private Switcher<Filter> textFilterSwitcher;
private Switcher<Filter> valueFilterSwitcher;
private Switcher<Formatter<Object>> formatterSwitcher;
private Filter templateFilter;
private Filter textFilter;
private Map<String, Template> importMacroTemplates = new ConcurrentHashMap<String, Template>();
private String[] importPackages;
private Set<String> importPackageSet;
private Map<String, Class<?>> importTypes;
private Map<Class<?>, Object> functions = new ConcurrentHashMap<Class<?>, Object>();
private List<StringSequence> sequences = new CopyOnWriteArrayList<StringSequence>();
private static final String TEMPLATE_CLASS_PREFIX = CompiledTemplate.class.getPackage().getName() + ".Template_";
private final AtomicInteger seq = new AtomicInteger();
private boolean sourceInClass;
private boolean textInClass;
private String outputEncoding;
private Class<?> defaultVariableType;
private Compiler compiler;
public void setCompiler(Compiler compiler) {
this.compiler = compiler;
}
public void setForVariable(String[] forVariable) {
this.forVariable = forVariable;
}
public void setImportSizers(String[] importSizers) {
this.importSizers = importSizers;
}
public void setTypes(Map<String, Class<?>> types) {
this.types = types;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public void setNode(Node node) {
this.node = node;
}
public void setOffset(int offset) {
this.offset = offset;
}
public void setStream(boolean stream) {
this.stream = stream;
}
public void setEngineName(String engineName) {
this.engineName = engineName;
}
public void setFilterVariable(String filterVariable) {
this.filterVariable = filterVariable;
}
public void setFormatterVariable(String formatterVariable) {
this.formatterVariable = formatterVariable;
}
public void setDefaultFilterVariable(String defaultFilterVariable) {
this.defaultFilterVariable = defaultFilterVariable;
}
public void setDefaultFormatterVariable(String defaultFormatterVariable) {
this.defaultFormatterVariable = defaultFormatterVariable;
}
public void setTextFilterSwitcher(Switcher<Filter> textFilterSwitcher) {
this.textFilterSwitcher = textFilterSwitcher;
}
public void setValueFilterSwitcher(Switcher<Filter> valueFilterSwitcher) {
this.valueFilterSwitcher = valueFilterSwitcher;
}
public void setFormatterSwitcher(Switcher<Formatter<Object>> formatterSwitcher) {
this.formatterSwitcher = formatterSwitcher;
}
public void setTemplateFilter(Filter templateFilter) {
this.templateFilter = templateFilter;
}
public void setTextFilter(Filter textFilter) {
this.textFilter = textFilter;
filterReference.set(textFilter);
}
public void setImportMacroTemplates(Map<String, Template> importMacroTemplates) {
this.importMacroTemplates = importMacroTemplates;
}
public void setImportPackages(String[] importPackages) {
this.importPackages = importPackages;
}
public void setImportPackageSet(Set<String> importPackageSet) {
this.importPackageSet = importPackageSet;
}
public void setImportTypes(Map<String, Class<?>> importTypes) {
this.importTypes = importTypes;
}
public void setImportMethods(Map<Class<?>, Object> functions) {
this.functions = functions;
}
public void setImportSequences(List<StringSequence> sequences) {
this.sequences = sequences;
}
public void setImportGetters(String[] importGetters) {
this.importGetters = importGetters;
}
public void setSourceInClass(boolean sourceInClass) {
this.sourceInClass = sourceInClass;
}
public void setTextInClass(boolean textInClass) {
this.textInClass = textInClass;
}
public void setOutputEncoding(String outputEncoding) {
this.outputEncoding = outputEncoding;
}
public void setDefaultVariableType(Class<?> defaultVariableType) {
this.defaultVariableType = defaultVariableType;
}
public CompiledVisitor() {
}
@Override
public boolean visit(Statement node) throws IOException, ParseException {
boolean result = super.visit(node);
filterKey = node.toString();
return result;
}
@Override
public void visit(Text node) throws IOException, ParseException {
String txt = node.getContent();
Filter filter = filterReference.get();
if (textFilterSwitcher != null || valueFilterSwitcher != null || formatterSwitcher != null) {
Set<String> locations = new HashSet<String>();
List<String> textLocations = textFilterSwitcher == null ? null : textFilterSwitcher.locations();
if (textLocations != null) {
locations.addAll(textLocations);
}
List<String> valueLocations = valueFilterSwitcher == null ? null : valueFilterSwitcher.locations();
if (valueLocations != null) {
locations.addAll(valueLocations);
}
List<String> formatterLocations = formatterSwitcher == null ? null : formatterSwitcher.locations();
if (formatterLocations != null) {
locations.addAll(formatterLocations);
}
if (locations != null && locations.size() > 0) {
Map<Integer, Set<String>> switchesd = new TreeMap<Integer, Set<String>>();
for (String location : locations) {
int i = -1;
while ((i = txt.indexOf(location, i + 1)) >= 0) {
Integer key = Integer.valueOf(i);
Set<String> values = switchesd.get(key);
if (values == null) {
values = new HashSet<String>();
switchesd.put(key, values);
}
values.add(location);
}
}
if (switchesd.size() > 0) {
getVariables.add(filterVariable);
int begin = 0;
for (Map.Entry<Integer, Set<String>> entry : switchesd.entrySet()) {
int end = entry.getKey();
String part = getTextPart(txt.substring(begin, end), filter, false);
if (StringUtils.isNotEmpty(part)) {
builder.append(" $output.write(" + part + ");\n");
}
begin = end;
for (String location : entry.getValue()) {
if (textLocations != null && textLocations.contains(location)) {
filter = textFilterSwitcher.switchover(location, textFilter);
filterReference.set(filter);
}
if (valueLocations != null && valueLocations.contains(location)) {
builder.append(" " + filterVariable + " = switchFilter(\"" + StringUtils.escapeString(location) + "\", " + defaultFilterVariable + ");\n");
}
if (formatterLocations != null && formatterLocations.contains(location)) {
builder.append(" " + formatterVariable + " = switchFormatter(\"" + StringUtils.escapeString(location) + "\", " + defaultFormatterVariable + ");\n");
}
}
}
if (begin > 0) {
txt = txt.substring(begin);
}
}
}
}
String part = getTextPart(txt, filter, false);
if (StringUtils.isNotEmpty(part)) {
builder.append(" $output.write(" + part + ");\n");
}
}
@Override
public void visit(ValueDirective node) throws IOException, ParseException {
boolean nofilter = node.isNoFilter();
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
getVariables.addAll(variableTypes.keySet());
if (Template.class.isAssignableFrom(returnType)) {
if (! StringUtils.isNamed(code)) {
code = "(" + code + ")";
}
builder.append(" if (");
builder.append(code);
builder.append(" != null) ");
builder.append(code);
builder.append(".render($output);\n");
} else if (nofilter && Resource.class.isAssignableFrom(returnType)) {
if (! StringUtils.isNamed(code)) {
code = "(" + code + ")";
}
builder.append(" ");
builder.append(IOUtils.class.getName());
builder.append(".copy(");
builder.append(code);
if (stream) {
builder.append(".openStream()");
} else {
builder.append(".openReader()");
}
builder.append(", $output);\n");
} else {
if (Object.class.equals(returnType)) {
if (! StringUtils.isNamed(code)) {
code = "(" + code + ")";
}
builder.append(" if (");
builder.append(code);
builder.append(" instanceof ");
builder.append(Template.class.getName());
builder.append(") {\n ((");
builder.append(Template.class.getName());
builder.append(")");
builder.append(code);
builder.append(").render($output);\n }");
if (nofilter) {
builder.append(" else if (");
builder.append(code);
builder.append(" instanceof ");
builder.append(Resource.class.getName());
builder.append(") {\n ");
builder.append(IOUtils.class.getName());
builder.append(".copy(((");
builder.append(Resource.class.getName());
builder.append(")");
builder.append(code);
if (stream) {
builder.append(").openStream()");
} else {
builder.append(").openReader()");
}
builder.append(", $output);\n }");
} else {
code = "(" + code + " instanceof " + Resource.class.getName() + " ? "
+ IOUtils.class.getName() + ".readToString(((" + Resource.class.getName() + ")"
+ code + ").openReader()) : " + code + ")";
}
builder.append(" else {\n");
} else if (Resource.class.isAssignableFrom(returnType)) {
if (! StringUtils.isNamed(code)) {
code = "(" + code + ")";
}
code = "(" + code + " == null ? null : " + IOUtils.class.getName() + ".readToString(" + code + ".openReader()))";
}
getVariables.add(formatterVariable);
String key = getTextPart(node.getExpression().toString(), null, true);
if (! stream && Object.class.equals(returnType)) {
String pre = "";
String var = "$obj" + seq.getAndIncrement();
pre = " Object " + var + " = " + code + ";\n";
String charsCode = "formatter.toChars(" + key + ", (char[]) " + var + ")";
code = "formatter.toString(" + key + ", " + var + ")";
if (! nofilter) {
getVariables.add(filterVariable);
charsCode = "doFilter(" + filterVariable + ", " + key + ", " + charsCode + ")";
code = "doFilter(" + filterVariable + ", " + key + ", " + code + ")";
}
builder.append(pre);
builder.append(" if (" + var + " instanceof char[]) $output.write(");
builder.append(charsCode);
builder.append("); else $output.write(");
builder.append(code);
builder.append(");\n");
} else {
if (stream) {
code = "formatter.toBytes(" + key + ", " + code + ")";
} else if (char[].class.equals(returnType)) {
code = "formatter.toChars(" + key + ", " + code + ")";
} else {
code = "formatter.toString(" + key + ", " + code + ")";
}
if (! nofilter) {
getVariables.add(filterVariable);
code = "doFilter(" + filterVariable + ", " + key + ", " + code + ")";
}
builder.append(" $output.write(");
builder.append(code);
builder.append(");\n");
}
if (Object.class.equals(returnType)) {
builder.append(" }\n");
}
}
}
@Override
public void visit(SetDirective node) throws IOException, ParseException {
Type type = node.getType();
Class<?> clazz = (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType) type).getRawType() : type);
if (node.getExpression() != null) {
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
if (clazz == null) {
clazz = returnType;
}
appendVar(clazz, node.getName(), code, node.isExport(), node.isHide(), node.getOffset());
getVariables.addAll(variableTypes.keySet());
} else {
clazz = checkVar(clazz, node.getName(), node.getOffset());
types.put(node.getName(), clazz);
if (type instanceof ParameterizedType) {
Type[] args = ((ParameterizedType) type).getActualTypeArguments();
for (int i = 0; i < args.length; i ++) {
Class<?> arg = (Class<?>) (args[i] instanceof ParameterizedType ? ((ParameterizedType) args[i]).getRawType() : args[i]);
types.put(node.getName() + ":" + i, arg);
}
}
defVariables.add(node.getName());
defVariableTypes.add(clazz);
}
}
private Class<?> checkVar(Class<?> clazz, String var, int offset) throws IOException, ParseException {
Class<?> cls = types.get(var);
if (cls != null && ! cls.equals(clazz)
&& ! cls.isAssignableFrom(clazz)
&& ! clazz.isAssignableFrom(cls)) {
throw new ParseException("Defined different type variable "
+ var + ", conflict types: " + cls.getCanonicalName() + ", " + clazz.getCanonicalName() + ".", offset);
}
if (cls != null && clazz.isAssignableFrom(cls)) {
return cls;
}
return clazz;
}
private void appendVar(Class<?> clazz, String var, String code, boolean parent, boolean hide, int offset) throws IOException, ParseException {
clazz = checkVar(clazz, var, offset);
String type = clazz.getCanonicalName();
types.put(var, clazz);
setVariables.add(var);
builder.append(" " + var + " = (" + type + ")(" + code + ");\n");
String ctx = null;
if (parent) {
ctx = "($context.getParent() != null ? $context.getParent() : $context)";
returnTypes.put(var, clazz);
} else if (! hide) {
ctx = "$context";
}
if (StringUtils.isNotEmpty(ctx)) {
builder.append(" " + ctx + ".put(\"");
builder.append(var);
builder.append("\", ");
builder.append(ClassUtils.class.getName() + ".boxed(" + var + ")");
builder.append(");\n");
}
}
@Override
public boolean visit(IfDirective node) throws IOException, ParseException {
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
builder.append(" if(");
builder.append(StringUtils.getConditionCode(returnType, code, importSizers));
builder.append(") {\n");
getVariables.addAll(variableTypes.keySet());
return true;
}
@Override
public void end(IfDirective node) throws IOException, ParseException {
builder.append(" }\n");
}
@Override
public boolean visit(ElseDirective node) throws IOException, ParseException {
if (node.getExpression() == null) {
builder.append(" else {\n");
} else {
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();builder.append(" else if (");
builder.append(StringUtils.getConditionCode(returnType, code, importSizers));
builder.append(") {\n");
getVariables.addAll(variableTypes.keySet());
}
return true;
}
@Override
public void end(ElseDirective node) throws IOException, ParseException {
builder.append(" }\n");
}
@Override
public boolean visit(ForDirective node) throws IOException, ParseException {
String var = node.getName();
Type type = node.getType();
Class<?> clazz = (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType) type).getRawType() : type);
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
String exprName = getGenericVariableName(node.getExpression());
if (clazz == null) {
if (returnType.isArray()) {
clazz = returnType.getComponentType();
} else if (Map.class.isAssignableFrom(returnType)) {
clazz = Map.Entry.class;
} else if (Collection.class.isAssignableFrom(returnType)) {
clazz = types.get(exprName + ":0"); // Collection<T>泛型
if (clazz == null) {
clazz = defaultVariableType;
}
} else {
clazz = defaultVariableType;
}
}
if (Map.class.isAssignableFrom(returnType)) {
Class<?> keyType = types.get(exprName + ":0");
if (keyType != null) {
types.put(var + ":0", keyType);
}
Class<?> valueType = types.get(exprName + ":1");
if (valueType != null) {
types.put(var + ":1", valueType);
}
code = ClassUtils.class.getName() + ".entrySet(" + code + ")";
}
int i = seq.incrementAndGet();
String dataName = "_d_" + i;
String sizeName = "_s_" + i;
String name = "_i_" + var;
builder.append(" " + Object.class.getSimpleName() + " " + dataName + " = " + code + ";\n");
builder.append(" int " + sizeName + " = " + ClassUtils.class.getName() + ".getSize(" + dataName + ");\n");
builder.append(" if (" + dataName + " != null && " + sizeName + " != 0) {\n");
builder.append(" ");
for (String fv : forVariable) {
builder.append(ClassUtils.filterJavaKeyword(fv));
builder.append(" = ");
}
builder.append("new " + Status.class.getName() + "(" + ClassUtils.filterJavaKeyword(forVariable[0]) + ", " + dataName + ", " + sizeName + ");\n");
builder.append(" for (" + Iterator.class.getName() + " " + name + " = " + CollectionUtils.class.getName() + ".toIterator(" + dataName + "); " + name + ".hasNext();) {\n");
String varCode;
if (clazz.isPrimitive()) {
varCode = ClassUtils.class.getName() + ".unboxed((" + ClassUtils.getBoxedClass(clazz).getSimpleName() + ")" + name + ".next())";
} else {
varCode = name + ".next()";
}
appendVar(clazz, var, varCode, false, false, node.getOffset());
getVariables.addAll(variableTypes.keySet());
for (String fv : forVariable) {
setVariables.add(fv);
}
return true;
}
@Override
public void end(ForDirective node) throws IOException, ParseException {
builder.append(" " + ClassUtils.filterJavaKeyword(forVariable[0]) + ".increment();\n }\n ");
for (String fv : forVariable) {
builder.append(ClassUtils.filterJavaKeyword(fv));
builder.append(" = ");
}
builder.append(ClassUtils.filterJavaKeyword(forVariable[0]) + ".getParent();\n }\n");
}
@Override
public void visit(BreakDirective node) throws IOException, ParseException {
String b = node.getParent() instanceof ForDirective ? "break" : "return";
if (node.getExpression() == null) {
if (! (node.getParent() instanceof IfDirective
|| node.getParent() instanceof ElseDirective)) {
throw new ParseException("Can not #break without condition. Please use #break(condition) or #if(condition) #break #end.", node.getOffset());
}
builder.append(" " + b + ";\n");
} else {
String code = popExpressionCode();
Class<?> returnType = popExpressionReturnType();
Map<String, Class<?>> variableTypes = popExpressionVariableTypes();
builder.append(" if(");
builder.append(StringUtils.getConditionCode(returnType, code, importSizers));
builder.append(") " + b + ";\n");
getVariables.addAll(variableTypes.keySet());
}
}
@Override
public boolean visit(MacroDirective node) throws IOException, ParseException {
types.put(node.getName(), Template.class);
CompiledVisitor visitor = new CompiledVisitor();
visitor.setResource(resource);
visitor.setNode(node);
visitor.setStream(stream);
visitor.setOffset(offset);
visitor.setDefaultFilterVariable(defaultFilterVariable);
visitor.setDefaultFormatterVariable(defaultFormatterVariable);
visitor.setDefaultVariableType(defaultVariableType);
visitor.setEngineName(engineName);
visitor.setFilterVariable(filterVariable);
visitor.setFormatterSwitcher(formatterSwitcher);
visitor.setFormatterVariable(formatterVariable);
visitor.setForVariable(forVariable);
visitor.setImportMacroTemplates(importMacroTemplates);
visitor.setImportPackages(importPackages);
visitor.setImportPackageSet(importPackageSet);
visitor.setImportSizers(importSizers);
visitor.setImportGetters(importGetters);
visitor.setImportTypes(importTypes);
visitor.setImportMethods(functions);
visitor.setOutputEncoding(outputEncoding);
visitor.setSourceInClass(sourceInClass);
visitor.setTemplateFilter(templateFilter);
visitor.setTextFilter(textFilter);
visitor.setTextFilterSwitcher(textFilterSwitcher);
visitor.setTextInClass(textInClass);
visitor.setValueFilterSwitcher(valueFilterSwitcher);
visitor.setCompiler(compiler);
visitor.init();
for (Node n : node.getChildren()) {
n.accept(visitor);
}
Class<?> macroType = visitor.compile();
macros.put(node.getName(), macroType);
return false;
}
public void init() {
if (types == null) {
types = new HashMap<String, Class<?>>();
}
if (importTypes != null && importTypes.size() > 0) {
types.putAll(importTypes);
}
types.put("this", Template.class);
types.put("super", Template.class);
types.put(defaultFilterVariable, Filter.class);
types.put(filterVariable, Filter.class);
types.put(defaultFormatterVariable, Formatter.class);
types.put(formatterVariable, Formatter.class);
for (String fv : forVariable) {
types.put(fv, Status.class);
}
for (String macro : importMacroTemplates.keySet()) {
types.put(macro, Template.class);
}
}
public Class<?> compile() throws IOException, ParseException {
String code = getCode();
return compiler.compile(code);
}
private String getCode() throws IOException, ParseException {
String name = getTemplateClassName(resource, node, stream);
String code = builder.toString();
int i = name.lastIndexOf('.');
String packageName = i < 0 ? "" : name.substring(0, i);
String className = i < 0 ? name : name.substring(i + 1);
StringBuilder imports = new StringBuilder();
String[] packages = importPackages;
if (packages != null && packages.length > 0) {
for (String pkg : packages) {
imports.append("import ");
imports.append(pkg);
imports.append(".*;\n");
}
}
Set<String> defined = new HashSet<String>();
StringBuilder statusInit = new StringBuilder();
StringBuilder macroFields = new StringBuilder();
StringBuilder macroInits = new StringBuilder();
StringBuilder declare = new StringBuilder();
if (getVariables.contains("this")) {
defined.add("this");
declare.append(" " + Template.class.getName() + " " + ClassUtils.filterJavaKeyword("this") + " = this;\n");
}
if (getVariables.contains("super")) {
defined.add("super");
declare.append(" " + Template.class.getName() + " " + ClassUtils.filterJavaKeyword("super") + " = ($context.getParent() == null ? null : $context.getParent().getTemplate());\n");
}
if (getVariables.contains(filterVariable)) {
defined.add(filterVariable);
defined.add(defaultFilterVariable);
declare.append(" " + Filter.class.getName() + " " + defaultFilterVariable + " = getFilter($context, \"" + filterVariable + "\");\n");
declare.append(" " + Filter.class.getName() + " " + filterVariable + " = " + defaultFilterVariable + ";\n");
}
if (getVariables.contains(formatterVariable)) {
defined.add(formatterVariable);
defined.add(defaultFormatterVariable);
declare.append(" " + MultiFormatter.class.getName() + " " + defaultFormatterVariable + " = getFormatter($context, \"" + formatterVariable + "\");\n");
declare.append(" " + MultiFormatter.class.getName() + " " + formatterVariable + " = " + defaultFormatterVariable + ";\n");
}
for (String var : defVariables) {
if (getVariables.contains(var) && ! defined.contains(var)) {
defined.add(var);
declare.append(getTypeCode(types.get(var), var));
}
}
Set<String> macroKeySet = macros.keySet();
for (String macro : macroKeySet) {
types.put(macro, Template.class);
if (getVariables.contains(macro) && ! defined.contains(macro)) {
defined.add(macro);
macroFields.append("private final " + Template.class.getName() + " " + macro + ";\n");
macroInits.append(" " + macro + " = getMacros().get(\"" + macro + "\");\n");
declare.append(" " + Template.class.getName() + " " + macro + " = getMacro($context, \"" + macro + "\", this." + macro + ");\n");
}
}
if (importTypes != null && importTypes.size() > 0) {
for (Map.Entry<String, Class<?>> entry : importTypes.entrySet()) {
String var = entry.getKey();
if (getVariables.contains(var) && ! defined.contains(var)) {
defined.add(var);
declare.append(getTypeCode(entry.getValue(), var));
}
}
}
for (String macro : importMacroTemplates.keySet()) {
if (getVariables.contains(macro) && ! defined.contains(macro)) {
defined.add(macro);
macroFields.append("private final " + Template.class.getName() + " " + macro + ";\n");
macroInits.append(" " + macro + " = getImportMacros().get(\"" + macro + "\");\n");
declare.append(" " + Template.class.getName() + " " + macro + " = getMacro($context, \"" + macro + "\", this." + macro + ");\n");
}
}
for (String var : setVariables) {
if (! defined.contains(var)) {
defined.add(var);
Class<?> type = types.get(var);
String typeName = getTypeName(type);
declare.append(" " + typeName + " " + ClassUtils.filterJavaKeyword(var) + " = " + ClassUtils.getInitCode(type) + ";\n");
}
}
for (String var : getVariables) {
if (! defined.contains(var)) {
Class<?> type = types.get(var);
if (type == null) {
type = defaultVariableType;
}
defined.add(var);
declare.append(getTypeCode(type, var));
defVariables.add(var);
defVariableTypes.add(type);
}
}
StringBuilder funtionFileds = new StringBuilder();
StringBuilder functionInits = new StringBuilder();
for (Map.Entry<Class<?>, Object> function : functions.entrySet()) {
Class<?> functionType = function.getKey();
if (function.getValue() instanceof Class) {
continue;
}
String pkgName = functionType.getPackage() == null ? null : functionType.getPackage().getName();
String typeName;
if (pkgName != null && ("java.lang".equals(pkgName)
|| (importPackageSet != null && importPackageSet.contains(pkgName)))) {
typeName = functionType.getSimpleName();
} else {
typeName = functionType.getCanonicalName();
}
funtionFileds.append("private final ");
funtionFileds.append(typeName);
funtionFileds.append(" $");
funtionFileds.append(functionType.getName().replace('.','_'));
funtionFileds.append(";\n");
functionInits.append(" this.$");
functionInits.append(functionType.getName().replace('.','_'));
functionInits.append(" = (");
functionInits.append(typeName);
functionInits.append(") functions.get(");
functionInits.append(typeName);
functionInits.append(".class);\n");
}
String methodCode = statusInit.toString() + declare + code;
textFields.append("private static final " + Map.class.getName() + " $VARS = " + toTypeCode(defVariables, defVariableTypes) + ";\n");
String templateName = resource.getName();
Node macro = node;
while (macro instanceof MacroDirective) {
templateName += "#" + ((MacroDirective) macro).getName();
macro = ((MacroDirective) macro).getParent();
}
String sorceCode = "package " + packageName + ";\n"
+ "\n"
+ imports.toString()
+ "\n"
+ "public final class " + className + " extends " + (stream ? OutputStreamTemplate.class.getName() : WriterTemplate.class.getName()) + " {\n"
+ "\n"
+ textFields
+ "\n"
+ funtionFileds
+ "\n"
+ macroFields
+ "\n"
+ "public " + className + "("
+ Engine.class.getName() + " engine, "
+ Interceptor.class.getName() + " interceptor, "
+ Compiler.class.getName() + " compiler, "
+ Switcher.class.getName() + " filterSwitcher, "
+ Switcher.class.getName() + " formatterSwitcher, "
+ Filter.class.getName() + " filter, "
+ Formatter.class.getName() + " formatter, "
+ Converter.class.getName() + " mapConverter, "
+ Converter.class.getName() + " outConverter, "
+ Map.class.getName() + " functions, "
+ Map.class.getName() + " importMacros, "
+ Resource.class.getName() + " resource, "
+ Template.class.getName() + " parent, "
+ Node.class.getName() + " root) {\n"
+ " super(engine, interceptor, compiler, filterSwitcher, formatterSwitcher, filter, formatter, mapConverter, outConverter, functions, importMacros, resource, parent, root);\n"
+ functionInits
+ macroInits
+ "}\n"
+ "\n"
+ "protected void doRender(" + Context.class.getName() + " $context, "
+ (stream ? OutputStream.class.getName() : Writer.class.getName())
+ " $output) throws " + Exception.class.getName() + " {\n"
+ methodCode
+ "}\n"
+ "\n"
+ "public " + String.class.getSimpleName() + " getName() {\n"
+ " return \"" + templateName + "\";\n"
+ "}\n"
+ "\n"
+ "public " + Map.class.getName() + " getVariables() {\n"
+ " return $VARS;\n"
+ "}\n"
+ "\n"
+ "protected " + Map.class.getName() + " getMacroTypes() {\n"
+ " return " + toTypeCode(macros) + ";\n"
+ "}\n"
+ "\n"
+ "public boolean isMacro() {\n"
+ " return " + (node instanceof MacroDirective) + ";\n"
+ "}\n"
+ "\n"
+ "public int getOffset() {\n"
+ " return " + offset + ";\n"
+ "}\n"
+ "\n"
+ "}\n";
return sorceCode;
}
private String getTypeName(Class<?> type) {
return type.getCanonicalName();
}
private String getTypeCode(Class<?> type, String var) {
String typeName = getTypeName(type);
if (type.isPrimitive()) {
return " " + typeName + " " + ClassUtils.filterJavaKeyword(var) + " = " + ClassUtils.class.getName() + ".unboxed((" + ClassUtils.getBoxedClass(type).getSimpleName() + ") $context.get(\"" + var + "\"));\n";
} else {
return " " + typeName + " " + ClassUtils.filterJavaKeyword(var) + " = (" + typeName + ") $context.get(\"" + var + "\");\n";
}
}
private String toTypeCode(Map<String, Class<?>> types) {
StringBuilder keyBuf = new StringBuilder();
StringBuilder valueBuf = new StringBuilder();
if (types == null || types.size() == 0) {
keyBuf.append("new String[0]");
valueBuf.append("new Class[0]");
} else {
keyBuf.append("new String[] {");
valueBuf.append("new Class[] {");
boolean first = true;
for (Map.Entry<String, Class<?>> entry : types.entrySet()) {
if (first) {
first = false;
} else {
keyBuf.append(", ");
valueBuf.append(", ");
}
keyBuf.append("\"");
keyBuf.append(StringUtils.escapeString(entry.getKey()));
keyBuf.append("\"");
valueBuf.append(entry.getValue().getCanonicalName());
valueBuf.append(".class");;
}
keyBuf.append("}");
valueBuf.append("}");
}
StringBuilder buf = new StringBuilder();
buf.append("new ");
buf.append(OrderedMap.class.getName());
buf.append("(");
buf.append(keyBuf);
buf.append(", ");
buf.append(valueBuf);
buf.append(")");
return buf.toString();
}
private String toTypeCode(List<String> names, List<Class<?>> types) {
StringBuilder buf = new StringBuilder();
buf.append("new ");
buf.append(OrderedMap.class.getName());
buf.append("(");
if (names == null || names.size() == 0) {
buf.append("new String[0]");
} else {
buf.append("new String[] {");
boolean first = true;
for (String str : names) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append("\"");
buf.append(StringUtils.escapeString(str));
buf.append("\"");
}
buf.append("}");
}
buf.append(", ");
if (names == null || names.size() == 0) {
buf.append("new Class[0]");
} else {
buf.append("new Class[] {");
boolean first = true;
for (Class<?> cls : types) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(cls.getCanonicalName());
buf.append(".class");
}
buf.append("}");
}
buf.append(")");
return buf.toString();
}
private String getTemplateClassName(Resource resource, Node node, boolean stream) {
String name = resource.getName();
String encoding = resource.getEncoding();
Locale locale = resource.getLocale();
long lastModified = resource.getLastModified();
StringBuilder buf = new StringBuilder(name.length() + 40);
buf.append(name);
Node macro = node;
while (macro instanceof MacroDirective) {
buf.append("_");
buf.append(((MacroDirective) macro).getName());
macro = ((MacroDirective) macro).getParent();
}
if (StringUtils.isNotEmpty(engineName)) {
buf.append("_");
buf.append(engineName);
}
if (StringUtils.isNotEmpty(encoding)) {
buf.append("_");
buf.append(encoding);
}
if (locale != null) {
buf.append("_");
buf.append(locale);
}
if (lastModified > 0) {
buf.append("_");
buf.append(lastModified);
}
buf.append(stream ? "_stream" : "_writer");
return TEMPLATE_CLASS_PREFIX + StringUtils.getVaildName(buf.toString());
}
private String getTextPart(String txt, Filter filter, boolean string) {
if (StringUtils.isNotEmpty(txt)) {
if (filter != null) {
txt = filter.filter(filterKey, txt);
}
String var = "$TXT" + seq.incrementAndGet();
if (string) {
if (textInClass) {
textFields.append("private static final String " + var + " = \"" + StringUtils.escapeString(txt) + "\";\n");
} else {
String txtId = StringCache.put(txt);
textFields.append("private static final String " + var + " = " + StringCache.class.getName() + ".getAndRemove(\"" + txtId + "\");\n");
}
} else if (stream) {
if (textInClass) {
textFields.append("private static final byte[] " + var + " = new byte[] {" + StringUtils.toByteString(StringUtils.toBytes(txt, outputEncoding)) + "};\n");
} else {
String txtId = ByteCache.put(StringUtils.toBytes(txt, outputEncoding));
textFields.append("private static final byte[] " + var + " = " + ByteCache.class.getName() + ".getAndRemove(\"" + txtId + "\");\n");
}
} else {
if (textInClass) {
textFields.append("private static final char[] " + var + " = new char[] {" + StringUtils.toCharString(txt.toCharArray()) + "};\n");
} else {
String txtId = CharCache.put(txt.toCharArray());
textFields.append("private static final char[] " + var + " = " + CharCache.class.getName() + ".getAndRemove(\"" + txtId + "\");\n");
}
}
return var;
}
return "";
}
private String popExpressionCode() {
String code = codeStack.pop();
if (! codeStack.isEmpty()) {
throw new IllegalStateException("Illegal expression.");
}
return code;
}
private Class<?> popExpressionReturnType() {
Type type = typeStack.pop();
if (! typeStack.isEmpty()) {
throw new IllegalStateException("Illegal expression.");
}
return (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType)type).getRawType() : type);
}
private Map<String, Class<?>> popExpressionVariableTypes() {
Map<String, Class<?>> types = variableTypes;
variableTypes = new HashMap<String, Class<?>>();
return types;
}
public void visit(Constant node) throws IOException, ParseException {
Object value = node.getValue();
Class<?> type;
String code;
if (value == null) {
type = node.isBoxed() ? void.class : null;
code = node.isBoxed() ? "" : "null";
} else if (value.equals(Boolean.TRUE)) {
type = node.isBoxed() ? Boolean.class : boolean.class;
code = node.isBoxed() ? "Boolean.TRUE" : "true";
} else if (value.equals(Boolean.FALSE)) {
type = node.isBoxed() ? Boolean.class : boolean.class;
code = node.isBoxed() ? "Boolean.FALSE" : "false";
} else if (value instanceof String) {
type = String.class;
code = "\"" + StringUtils.escapeString((String) value) + "\"";
} else if (value instanceof Character) {
type = node.isBoxed() ? Character.class : char.class;
code = node.isBoxed() ? "Character.valueOf('" + StringUtils.escapeString(String.valueOf(value)) + "')"
: "'" + StringUtils.escapeString(String.valueOf(value)) + "'";
} else if (value instanceof Double) {
type = node.isBoxed() ? Double.class : double.class;
code = node.isBoxed() ? "Double.valueOf(" + value + "d)" : value + "d";
} else if (value instanceof Float) {
type = node.isBoxed() ? Float.class : float.class;
code = node.isBoxed() ? "Float.valueOf(" + value + "f)" : value + "f";
} else if (value instanceof Long) {
type = node.isBoxed() ? Long.class : long.class;
code = node.isBoxed() ? "Long.valueOf(" + value + "l)" : value + "l";
} else if (value instanceof Short) {
type = node.isBoxed() ? Short.class : short.class;
code = node.isBoxed() ? "Short.valueOf((short)" + value + ")" : "((short)" + value + ")";
} else if (value instanceof Byte) {
type = node.isBoxed() ? Byte.class : byte.class;
code = node.isBoxed() ? "Byte.valueOf((byte)" + value + ")" : "((byte)" + value + ")";
} else if (value instanceof Integer) {
type = node.isBoxed() ? Integer.class : int.class;
code = node.isBoxed() ? "Integer.valueOf(" + value + ")" : String.valueOf(value);
} else if (value instanceof Class) {
type = node.isBoxed() ? ClassUtils.getBoxedClass((Class<?>) value) : (Class<?>) value;
code = ((Class<?>) value).getCanonicalName();
} else {
throw new ParseException("Unsupported constant " + value, node.getOffset());
}
typeStack.push(type);
codeStack.push(code);
}
public void visit(Variable node) throws IOException, ParseException {
String name = node.getName();
Class<?> type = types.get(name);
if (type == null) {
type = defaultVariableType;
if (type == null) {
type = Object.class;
}
}
String code = ClassUtils.filterJavaKeyword(name);
typeStack.push(type);
codeStack.push(code);
variableTypes.put(name, type);
}
@Override
public void visit(PositiveOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Type type = parameterType;
String code = parameterCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(NegativeOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
String name = node.getName();
Type type = parameterClass;
String code;
if (node.getParameter() instanceof Operator
&& ((Operator) node.getParameter()).getPriority() < node.getPriority()) {
code = name + " (" + parameterCode + ")";
} else {
code = name + " " + parameterCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(NotOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
Type type = boolean.class;
String code = "! (" + StringUtils.getConditionCode(parameterClass, parameterCode, importSizers) + ")";
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(BitNotOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
String name = node.getName();
Type type = parameterClass;
String code;
if (node.getParameter() instanceof Operator
&& ((Operator) node.getParameter()).getPriority() < node.getPriority()) {
code = name + " (" + parameterCode + ")";
} else {
code = name + " " + parameterCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(ListOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
Type type = null;
String code = null;
if (parameterType instanceof ParameterizedType) {
parameterClass = (Class<?>)((ParameterizedType) parameterType).getActualTypeArguments()[0];
}
if (Map.Entry.class.isAssignableFrom(parameterClass)) {
type = Map.class;
code = CollectionUtils.class.getName() + ".toMap(new " + Map.Entry.class.getCanonicalName() + "[] {" + parameterCode + "})";
} else {
type = Array.newInstance(parameterClass, 0).getClass();
code = "new " + parameterClass.getCanonicalName() + "[] {" + parameterCode + "}";
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(NewOperator node) throws IOException, ParseException {
typeStack.pop();
String parameterCode = codeStack.pop();
String name = node.getName();
Type type = ClassUtils.forName(importPackages, name);
String code = "new " + name + "(" + parameterCode + ")";
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(StaticMethodOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
Class<?> parameterClass = (Class<?>) (parameterType instanceof ParameterizedType ? ((ParameterizedType)parameterType).getRawType() : parameterType);
String name = node.getName();
Type type = null;
String code = null;
Class<?>[] parameterTypes;
if (parameterType instanceof ParameterizedType) {
parameterTypes = (Class<?>[]) ((ParameterizedType) parameterType).getActualTypeArguments();
} else if (parameterClass == void.class) {
parameterTypes = new Class<?>[0];
} else {
parameterTypes = new Class<?>[] { parameterClass };
}
Class<?> t = types.get(name);
if (t != null && Template.class.isAssignableFrom(t)) {
variableTypes.put(name, Template.class);
type = Object.class;
code = "(" + name + " == null ? null : " + name + ".evaluate(new Object" + (parameterCode.length() == 0 ? "[0]" : "[] { " + parameterCode + " }") + "))";
} else {
name = ClassUtils.filterJavaKeyword(name);
type = null;
code = null;
if (functions != null && functions.size() > 0) {
for (Class<?> function : functions.keySet()) {
try {
Method method = ClassUtils.searchMethod(function, name, parameterTypes);
if (Object.class.equals(method.getDeclaringClass())) {
break;
}
type = method.getReturnType();
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + function.getName(), node.getOffset());
}
if (Modifier.isStatic(method.getModifiers())) {
code = function.getName() + "." + method.getName() + "(" + parameterCode + ")";
} else {
code = "$" + function.getName().replace('.', '_') + "." + method.getName() + "(" + parameterCode + ")";
}
break;
} catch (NoSuchMethodException e) {
}
}
}
if (code == null) {
throw new ParseException("No such macro \"" + name + "\" or import method " + ClassUtils.getMethodFullName(name, parameterTypes) + ".", node.getOffset());
}
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(CastOperator node) throws IOException, ParseException {
Type parameterType = typeStack.pop();
String parameterCode = codeStack.pop();
String name = node.getName();
Type type = ClassUtils.forName(importPackages, name);
String code = parameterCode;
if (! type.equals(parameterType)) {
code = "(" + name + ")(" + parameterCode + ")";
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(AddOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if ((Collection.class.isAssignableFrom(leftClass) || leftClass.isArray())
&& (Collection.class.isAssignableFrom(rightClass) || rightClass.isArray())
|| Map.class.isAssignableFrom(leftClass) && Map.class.isAssignableFrom(rightClass)) {
code = CollectionUtils.class.getName() + ".merge(" + leftCode+ ", " + rightCode + ")";
type = leftType;
} else if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = String.class;
}
if (type != String.class) {
Class<?> clazz = (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType)type).getRawType() : type);
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(SubOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type;
if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = int.class;
}
Class<?> clazz = (Class<?>) type;
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(MulOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type;
if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = int.class;
}
Class<?> clazz = (Class<?>) type;
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(DivOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type;
if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = int.class;
}
Class<?> clazz = (Class<?>) type;
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(ModOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type;
if (rightClass.isPrimitive() && rightType != boolean.class) {
type = rightClass;
} else if (leftClass.isPrimitive() && leftClass != boolean.class) {
type = leftClass;
} else {
type = int.class;
}
Class<?> clazz = (Class<?>) type;
String typeName = clazz.getCanonicalName();
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
if (! (leftClass.isPrimitive() && leftClass != boolean.class)) {
leftCode = ClassUtils.class.getName() + ".to" + typeName + "(" + leftCode + ")";
}
if (! (rightClass.isPrimitive() && leftClass != boolean.class)) {
rightCode = ClassUtils.class.getName() + ".to" + typeName + "(" + rightCode + ")";
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(EqualsOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code;
if(! "null".equals(leftCode) && ! "null".equals(rightCode)
&& ! leftClass.isPrimitive() && ! rightClass.isPrimitive()) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".equals(" + rightCode + ")");
} else {
code = leftCode + " == " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(NotEqualsOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code;
if(! "null".equals(leftCode) && ! "null".equals(rightCode)
&& ! leftClass.isPrimitive() && ! rightClass.isPrimitive()) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "(! " + leftCode + ".equals(" + rightCode + "))");
} else {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(GreaterOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = null;
if (leftClass != null && Comparable.class.isAssignableFrom(leftClass)) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".compareTo(" + rightCode + ") > 0");
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(GreaterEqualsOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = null;
if (leftClass != null && Comparable.class.isAssignableFrom(leftClass)) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".compareTo(" + rightCode + ") >= 0");
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(LessOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = null;
if (leftClass != null && Comparable.class.isAssignableFrom(leftClass)) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".compareTo(" + rightCode + ") < 0");
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(LessEqualsOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = null;
if (leftClass != null && Comparable.class.isAssignableFrom(leftClass)) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".compareTo(" + rightCode + ") <= 0");
}
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
if (code == null) {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(AndOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
if(! boolean.class.equals(leftClass)) {
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
leftCode = StringUtils.getConditionCode(leftClass, leftCode, importSizers);
rightCode = StringUtils.getConditionCode(rightClass, rightCode, importSizers);
}
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(OrOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftClass;
String code = null;
if(! boolean.class.equals(leftClass)) {
code = "(" + StringUtils.getConditionCode(leftClass, leftCode, importSizers) + " ? (" + leftCode + ") : (" + rightCode + "))";
} else {
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(BitAndOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(BitOrOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(BitXorOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(RightShiftOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(LeftShiftOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(UnsignShiftOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = leftType;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(ArrayOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
List<Class<?>> ts = new ArrayList<Class<?>>();
if (leftType instanceof ParameterizedType) {
for (Type t : ((ParameterizedType) leftType).getActualTypeArguments()) {
ts.add((Class<?>) t);
}
} else if (leftType != void.class) {
ts.add((Class<?>) leftType);
}
if (rightType instanceof ParameterizedType) {
for (Type t : ((ParameterizedType) rightType).getActualTypeArguments()) {
ts.add((Class<?>) t);
}
} else if (rightType != void.class) {
ts.add((Class<?>) rightType);
}
type = new ParameterizedTypeImpl(Object[].class, ts.toArray(new Class<?>[ts.size()]));
code = leftCode + ", " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(ConditionOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = rightClass;
if (node.getRightParameter() instanceof Operator
&& ((Operator) node.getRightParameter()).getPriority() < node.getPriority()) {
rightCode = "(" + rightCode + ")";
}
leftCode = StringUtils.getConditionCode(leftClass, leftCode, importSizers);
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(EntryOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if(! (node.getLeftParameter() instanceof BinaryOperator
&& "?".equals(((BinaryOperator)node.getLeftParameter()).getName()))) {
type = Map.Entry.class;
code = "new " + MapEntry.class.getName() + "(" + leftCode + ", " + rightCode + ")";
} else {
type = leftType;
code = leftCode + " " + name + " " + rightCode;
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(InstanceofOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
typeStack.pop();
String leftCode = codeStack.pop();
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = boolean.class;
String code = leftCode + " " + name + " " + rightCode;
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(IndexOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
if (node.getLeftParameter() instanceof Operator) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if (Map.class.isAssignableFrom(leftClass)) {
String var = getGenericVariableName(node.getLeftParameter());
if (var != null && types.containsKey(var + ":1")) {
Class<?> varType = types.get(var + ":1"); // Map<K,V>第二个泛型
type = varType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + varType.getCanonicalName() + ")" + leftCode + ".get(" + rightCode + "))");
} else {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".get(" + rightCode + ")");
}
} else if (List.class.isAssignableFrom(leftClass)) {
if (int[].class == rightType) {
type = List.class;;
code = CollectionUtils.class.getName() + ".subList(" + leftCode + ", " + rightCode + ")";
} else if (rightType instanceof ParameterizedType
&& ((ParameterizedType) rightType).getActualTypeArguments()[0] == int.class) {
type = List.class;;
code = CollectionUtils.class.getName() + ".subList(" + leftCode + ", new int[] {" + rightCode + "})";
} else if (int.class.equals(rightType)) {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".get(" + rightCode + ")");
if (node.getLeftParameter() instanceof Variable) {
String var = ((Variable)node.getLeftParameter()).getName();
Class<?> varType = types.get(var + ":0"); // List<T>第一个泛型
if (varType != null) {
type = varType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + varType.getCanonicalName() + ")" + leftCode + ".get(" + rightCode + "))");
}
}
} else {
throw new ParseException("The \"[]\" index type: " + rightType + " must be int!", node.getOffset());
}
} else if (leftClass.isArray()) {
if (int[].class == rightType) {
type = leftClass;
code = CollectionUtils.class.getName() + ".subArray(" + leftCode + ", " + rightCode + ")";
} else if (rightType instanceof ParameterizedType
&& ((ParameterizedType) rightType).getActualTypeArguments()[0] == int.class) {
type = leftClass;
code = CollectionUtils.class.getName() + ".subArray(" + leftCode + ", new int[] {" + rightCode + "})";
} else if (int.class.equals(rightType)) {
type = leftClass.getComponentType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "[" + rightCode + "]");
} else {
throw new ParseException("The \"[]\" index type: " + rightType + " must be int!", node.getOffset());
}
} else {
throw new ParseException("Unsuptorted \"[]\" for non-array type: " + leftClass, node.getOffset());
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(SequenceOperator node) throws IOException, ParseException {
typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if (leftClass == int.class || leftClass == Integer.class
|| leftClass == short.class || leftClass == Short.class
|| leftClass == long.class || leftClass == Long.class
|| leftClass == char.class || leftClass == Character.class) {
type = Array.newInstance(leftClass, 0).getClass();
code = CollectionUtils.class.getName() + ".createSequence(" + leftCode + ", " + rightCode + ")";
} else if (leftClass == String.class
&& leftCode.length() >= 2 && rightCode.length() >= 2
&& (leftCode.startsWith("\"") || leftCode.startsWith("\'"))
&& (leftCode.endsWith("\"") || leftCode.endsWith("\'"))
&& (rightCode.startsWith("\"") || rightCode.startsWith("\'"))
&& (rightCode.endsWith("\"") || rightCode.endsWith("\'"))) {
type = String[].class;
StringBuilder buf = new StringBuilder();
for (String s : getSequence(leftCode.substring(1, leftCode.length() - 1),
rightCode.substring(1, rightCode.length() - 1))) {
if (buf.length() > 0) {
buf.append(",");
}
buf.append("\"");
buf.append(s);
buf.append("\"");
}
code = "new String[] {" + buf.toString() + "}";
} else {
throw new ParseException("The operator \"..\" unsupported parameter type " + leftClass, node.getOffset());
}
typeStack.push(type);
codeStack.push(code);
}
@Override
public void visit(MethodOperator node) throws IOException, ParseException {
Type rightType = typeStack.pop();
String rightCode = codeStack.pop();
Type leftType = typeStack.pop();
String leftCode = codeStack.pop();
Class<?> rightClass = (Class<?>) (rightType instanceof ParameterizedType ? ((ParameterizedType)rightType).getRawType() : rightType);
Class<?> leftClass = (Class<?>) (leftType instanceof ParameterizedType ? ((ParameterizedType)leftType).getRawType() : leftType);
String name = node.getName();
if (node.getLeftParameter() instanceof Operator
&& ((Operator) node.getLeftParameter()).getPriority() < node.getPriority()) {
leftCode = "(" + leftCode + ")";
}
Type type = null;
String code = null;
if ("to".equals(name)
&& node.getRightParameter() instanceof Constant
&& rightType == String.class
&& rightCode.length() > 2
&& rightCode.startsWith("\"") && rightCode.endsWith("\"")) {
code = "((" + rightCode.substring(1, rightCode.length() - 1) + ")" + leftCode + ")";
type = ClassUtils.forName(importPackages, rightCode.substring(1, rightCode.length() - 1));
} else if ("class".equals(name)) {
type = Class.class;
if (leftClass.isPrimitive()) {
code = leftClass.getCanonicalName() + ".class";
} else {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".getClass()");
}
} else if (Map.Entry.class.isAssignableFrom(leftClass)
&& ("key".equals(name) || "value".equals(name))) {
String var = getGenericVariableName(node.getLeftParameter());
if (var != null) {
Class<?> keyType = types.get(var + ":0"); // Map<K,V>第一个泛型
Class<?> valueType = types.get(var + ":1"); // Map<K,V>第二个泛型
if ("key".equals(name) && keyType != null) {
type = keyType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + keyType.getCanonicalName() + ")" + leftCode + ".getKey(" + rightCode + "))");
} else if ("value".equals(name) && valueType != null) {
type = valueType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + valueType.getCanonicalName() + ")" + leftCode + ".getValue(" + rightCode + "))");
}
}
} else if (Map.class.isAssignableFrom(leftClass)
&& "get".equals(name)
&& String.class.equals(rightType)) {
String var = getGenericVariableName(node.getLeftParameter());
if (var != null) {
Class<?> varType = types.get(var + ":1"); // Map<K,V>第二个泛型
if (varType != null) {
type = varType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + varType.getCanonicalName() + ")" + leftCode + ".get(" + rightCode + "))");
}
}
} else if (List.class.isAssignableFrom(leftClass)
&& "get".equals(name)
&& int.class.equals(rightType)) {
String var = getGenericVariableName(node.getLeftParameter());
if (var != null) {
Class<?> varType = types.get(var + ":0"); // List<T>第一个泛型
if (varType != null) {
type = varType;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + varType.getCanonicalName() + ")" + leftCode + ".get(" + rightCode + "))");
}
}
}
if (code == null) {
Class<?>[] rightTypes;
if (rightType instanceof ParameterizedType) {
rightTypes = (Class<?>[]) ((ParameterizedType) rightType).getActualTypeArguments();
} else if (rightClass == void.class) {
rightTypes = new Class<?>[0];
} else {
rightTypes = new Class<?>[] { rightClass };
}
if (Template.class.isAssignableFrom(leftClass)
&& ! hasMethod(Template.class, name, rightTypes)) {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, CompiledVisitor.class.getName() + ".getMacro(" + leftCode + ", \"" + name + "\").evaluate(new Object" + (rightCode.length() == 0 ? "[0]" : "[] { " + rightCode + " }") + ")");
} else if (Map.class.isAssignableFrom(leftClass)
&& rightTypes.length == 0
&& ! hasMethod(Map.class, name, rightTypes)) {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".get(\"" + name + "\")");
String var = getGenericVariableName(node.getLeftParameter());
if (var != null) {
Class<?> t = types.get(var + ":1"); // Map<K,V>第二个泛型
if (t != null) {
type = t;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, "((" + t.getCanonicalName() + ")" + leftCode + ".get(\"" + name + "\"))");
}
}
} else if (importGetters != null && importGetters.length > 0
&& rightTypes.length == 0
&& ! hasMethod(leftClass, name, rightTypes)) {
for (String getter : importGetters) {
if (hasMethod(leftClass, getter, new Class<?>[] { String.class })
|| hasMethod(leftClass, getter, new Class<?>[] { Object.class })) {
type = Object.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + getter + "(\"" + name + "\")");
break;
}
}
}
name = ClassUtils.filterJavaKeyword(name);
if (functions != null && functions.size() > 0) {
Class<?>[] allTypes;
String allCode;
if (rightTypes == null || rightTypes.length == 0) {
allTypes = new Class<?>[] {leftClass};
allCode = leftCode;
} else {
allTypes = new Class<?>[rightTypes.length + 1];
allTypes[0] = leftClass;
System.arraycopy(rightTypes, 0, allTypes, 1, rightTypes.length);
allCode = leftCode + ", " + rightCode;
}
for (Class<?> function : functions.keySet()) {
try {
Method method = ClassUtils.searchMethod(function, name, allTypes);
if (! Object.class.equals(method.getDeclaringClass())) {
type = method.getReturnType();
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + function.getName(), node.getOffset());
}
if (Modifier.isStatic(method.getModifiers())) {
code = getNotNullCode(node.getLeftParameter(), type, leftCode, function.getName() + "." + method.getName() + "(" + allCode + ")");
} else {
code = "$" + function.getName().replace('.', '_') + "." + method.getName() + "(" + allCode + ")";
}
break;
}
} catch (NoSuchMethodException e) {
}
}
}
if (code == null) {
if (leftClass.isArray() && "length".equals(name)) {
type = int.class;
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + ".length");
} else {
try {
Method method = ClassUtils.searchMethod(leftClass, name, rightTypes);
type = method.getReturnType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + method.getName() + "(" + rightCode + ")");
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + leftClass.getName(), node.getOffset());
}
} catch (NoSuchMethodException e) {
String def = "";
if (StringUtils.isNamed(leftCode) && leftClass.equals(defaultVariableType)) {
def = " Please add variable type definition #set(Xxx " + leftCode + ") in your template.";
}
if (rightTypes != null && rightTypes.length > 0) {
throw new ParseException("No such method " + ClassUtils.getMethodFullName(name, rightTypes) + " in class "
+ leftClass.getName() + "." + def, node.getOffset());
} else { // search property
try {
String getter = "get" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method method = leftClass.getMethod(getter,
new Class<?>[0]);
type = method.getReturnType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + method.getName() + "()");
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + leftClass.getName(), node.getOffset());
}
} catch (NoSuchMethodException e2) {
try {
String getter = "is"
+ name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method method = leftClass.getMethod(getter,
new Class<?>[0]);
type = method.getReturnType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + method.getName() + "()");
if (type == void.class) {
throw new ParseException("Can not call void method " + method.getName() + " in class " + leftClass.getName(), node.getOffset());
}
} catch (NoSuchMethodException e3) {
try {
Field field = leftClass.getField(name);
type = field.getType();
code = getNotNullCode(node.getLeftParameter(), type, leftCode, leftCode + "." + field.getName());
} catch (NoSuchFieldException e4) {
throw new ParseException(
"No such property "
+ name
+ " in class "
+ leftClass.getName()
+ ", because no such method get"
+ name.substring(0, 1)
.toUpperCase()
+ name.substring(1)
+ "() or method is"
+ name.substring(0, 1)
.toUpperCase()
+ name.substring(1)
+ "() or method " + name
+ "() or filed " + name + "." + def, node.getOffset());
}
}
}
}
}
}
}
}
typeStack.push(type);
codeStack.push(code);
}
private static String getGenericVariableName(Expression node) {
if (node instanceof Variable) {
return ((Variable)node).getName();
}
while (node instanceof BinaryOperator) {
String name = ((BinaryOperator)node).getName();
if ("+".equals(name) || "||".equals(name)
|| "&&".equals(name)
|| ".entrySet".equals(name)) {
node = ((BinaryOperator)node).getLeftParameter();
if (node instanceof Variable) {
return ((Variable)node).getName();
}
} else {
return null;
}
}
return null;
}
private List<String> getSequence(String begin, String end) {
if (sequences != null) {
for (StringSequence sequence : sequences) {
if (sequence.containSequence(begin, end)) {
return sequence.getSequence(begin, end);
}
}
}
throw new IllegalStateException("No such sequence from \"" + begin + "\" to \"" + end + "\".");
}
public static Template getMacro(Template template, String name) {
Template macro = template.getMacros().get(name);
if (macro == null) {
throw new IllegalStateException("No such macro " + name + "in template " + template.getName());
}
return macro;
}
private String getNotNullCode(Node leftParameter, Type type, String leftCode, String code) throws IOException, ParseException {
if (leftParameter instanceof Constant) {
return code;
}
Class<?> clazz = (Class<?>) (type instanceof ParameterizedType ? ((ParameterizedType)type).getRawType() : type);
return "(" + leftCode + " == null ? (" + clazz.getCanonicalName() + ")" + ClassUtils.getInitCode(clazz) + " : " + code + ")";
}
private boolean hasMethod(Class<?> leftClass, String name, Class<?>[] rightTypes) {
if (leftClass == null) {
return false;
}
if (leftClass.isArray() && "length".equals(name)) {
return true;
}
try {
Method method = ClassUtils.searchMethod(leftClass, name, rightTypes);
return method != null;
} catch (NoSuchMethodException e) {
if (rightTypes != null && rightTypes.length > 0) {
return false;
} else { // search property
try {
String getter = "get" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method method = leftClass.getMethod(getter,
new Class<?>[0]);
return method != null;
} catch (NoSuchMethodException e2) {
try {
String getter = "is"
+ name.substring(0, 1).toUpperCase()
+ name.substring(1);
Method method = leftClass.getMethod(getter,
new Class<?>[0]);
return method != null;
} catch (NoSuchMethodException e3) {
try {
Field field = leftClass.getField(name);
return field != null;
} catch (NoSuchFieldException e4) {
return false;
}
}
}
}
}
}
} | #118 #set推导类型不作为声明
| httl/src/main/java/httl/spi/translators/templates/CompiledVisitor.java | #118 #set推导类型不作为声明 |
|
Java | bsd-2-clause | 6b855ea76f320b044ab9db72ff0c87cafe1860fc | 0 | TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2013 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.updater.gui;
import imagej.updater.core.Checksummer;
import imagej.updater.core.Diff.Mode;
import imagej.updater.core.FileObject;
import imagej.updater.core.FileObject.Action;
import imagej.updater.core.FileObject.Status;
import imagej.updater.core.FilesCollection;
import imagej.updater.core.FilesCollection.DependencyMap;
import imagej.updater.core.FilesUploader;
import imagej.updater.core.Installer;
import imagej.updater.core.UploaderService;
import imagej.updater.util.Progress;
import imagej.updater.util.UpdateCanceledException;
import imagej.updater.util.UpdaterUserInterface;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.scijava.Context;
import org.scijava.log.LogService;
import org.scijava.util.ProcessUtils;
/**
* TODO
*
* @author Johannes Schindelin
*/
@SuppressWarnings("serial")
public class UpdaterFrame extends JFrame implements TableModelListener,
ListSelectionListener
{
protected LogService log;
private UploaderService uploaderService;
protected FilesCollection files;
protected JTextField searchTerm;
protected JPanel searchPanel;
protected ViewOptions viewOptions;
protected JPanel viewOptionsPanel;
protected JPanel chooseLabel;
protected FileTable table;
protected JLabel fileSummary;
protected JPanel summaryPanel;
protected JPanel rightPanel;
protected FileDetails fileDetails;
protected JButton apply, cancel, easy, updateSites;
protected boolean easyMode;
// For developers
protected JButton upload, showChanges, rebuildButton;
protected boolean canUpload;
protected final static String gitVersion;
static {
String version = null;
try {
version = ProcessUtils.exec(null, null, null, "git", "--version");
} catch (Throwable t) { /* ignore */ }
gitVersion = version;
}
public UpdaterFrame(final LogService log,
final UploaderService uploaderService, final FilesCollection files)
{
super("ImageJ Updater");
setPreferredSize(new Dimension(780, 560));
this.log = log;
this.uploaderService = uploaderService;
this.files = files;
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
quit();
}
});
// ======== Start: LEFT PANEL ========
final JPanel leftPanel = new JPanel();
final GridBagLayout gb = new GridBagLayout();
leftPanel.setLayout(gb);
final GridBagConstraints c = new GridBagConstraints(0, 0, // x, y
9, 1, // rows, cols
0, 0, // weightx, weighty
GridBagConstraints.NORTHWEST, // anchor
GridBagConstraints.HORIZONTAL, // fill
new Insets(0, 0, 0, 0), 0, 0); // ipadx, ipady
searchTerm = new JTextField();
searchTerm.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(final DocumentEvent e) {
updateFilesTable();
}
@Override
public void removeUpdate(final DocumentEvent e) {
updateFilesTable();
}
@Override
public void insertUpdate(final DocumentEvent e) {
updateFilesTable();
}
});
searchPanel = SwingTools.labelComponentRigid("Search:", searchTerm);
gb.setConstraints(searchPanel, c);
leftPanel.add(searchPanel);
Component box = Box.createRigidArea(new Dimension(0, 10));
c.gridy = 1;
gb.setConstraints(box, c);
leftPanel.add(box);
viewOptions = new ViewOptions();
viewOptions.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
updateFilesTable();
}
});
viewOptionsPanel =
SwingTools.labelComponentRigid("View Options:", viewOptions);
c.gridy = 2;
gb.setConstraints(viewOptionsPanel, c);
leftPanel.add(viewOptionsPanel);
box = Box.createRigidArea(new Dimension(0, 10));
c.gridy = 3;
gb.setConstraints(box, c);
leftPanel.add(box);
// Create labels to annotate table
chooseLabel =
SwingTools.label("Please choose what you want to install/uninstall:",
null);
c.gridy = 4;
gb.setConstraints(chooseLabel, c);
leftPanel.add(chooseLabel);
box = Box.createRigidArea(new Dimension(0, 5));
c.gridy = 5;
gb.setConstraints(box, c);
leftPanel.add(box);
// Label text for file summaries
fileSummary = new JLabel();
summaryPanel = SwingTools.horizontalPanel();
summaryPanel.add(fileSummary);
summaryPanel.add(Box.createHorizontalGlue());
// Create the file table and set up its scrollpane
table = new FileTable(this);
table.getSelectionModel().addListSelectionListener(this);
final JScrollPane fileListScrollpane = new JScrollPane(table);
fileListScrollpane.getViewport().setBackground(table.getBackground());
c.gridy = 6;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
gb.setConstraints(fileListScrollpane, c);
leftPanel.add(fileListScrollpane);
box = Box.createRigidArea(new Dimension(0, 5));
c.gridy = 7;
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
gb.setConstraints(box, c);
leftPanel.add(box);
// ======== End: LEFT PANEL ========
// ======== Start: RIGHT PANEL ========
rightPanel = SwingTools.verticalPanel();
rightPanel.add(Box.createVerticalGlue());
fileDetails = new FileDetails(this);
SwingTools.tab(fileDetails, "Details", "Individual file information", 350,
315, rightPanel);
// TODO: put this into SwingTools, too
rightPanel.add(Box.createRigidArea(new Dimension(0, 25)));
// ======== End: RIGHT PANEL ========
// ======== Start: TOP PANEL (LEFT + RIGHT) ========
final JPanel topPanel = SwingTools.horizontalPanel();
topPanel.add(leftPanel);
topPanel.add(Box.createRigidArea(new Dimension(15, 0)));
topPanel.add(rightPanel);
topPanel.setBorder(BorderFactory.createEmptyBorder(20, 15, 5, 15));
// ======== End: TOP PANEL (LEFT + RIGHT) ========
// ======== Start: BOTTOM PANEL ========
final JPanel bottomPanel2 = SwingTools.horizontalPanel();
final JPanel bottomPanel = SwingTools.horizontalPanel();
bottomPanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 15, 15));
bottomPanel.add(new FileAction("Keep as-is", null));
bottomPanel.add(Box.createRigidArea(new Dimension(15, 0)));
bottomPanel.add(new FileAction("Install", Action.INSTALL, "Update",
Action.UPDATE));
bottomPanel.add(Box.createRigidArea(new Dimension(15, 0)));
bottomPanel.add(new FileAction("Uninstall", Action.UNINSTALL));
bottomPanel.add(Box.createHorizontalGlue());
// make sure that sezpoz finds the classes when triggered from the EDT
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
SwingTools.invokeOnEDT(new Runnable() {
@Override
public void run() {
if (contextClassLoader != null)
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
});
// Button to start actions
apply =
SwingTools.button("Apply changes", "Start installing/uninstalling files",
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
applyChanges();
}
}, bottomPanel);
apply.setEnabled(files.hasChanges());
// Manage update sites
updateSites =
SwingTools.button("Manage update sites",
"Manage multiple update sites for updating and uploading",
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
new SitesDialog(UpdaterFrame.this, UpdaterFrame.this.files).setVisible(true);
}
}, bottomPanel2);
// TODO: unify upload & apply changes (probably apply changes first, then
// upload)
// includes button to upload to server if is a Developer using
bottomPanel2.add(Box.createRigidArea(new Dimension(15, 0)));
upload =
SwingTools.button("Upload to server", "Upload selected files to server",
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
try {
upload();
}
catch (final InstantiationException e) {
log.error(e);
error("Could not upload (possibly unknown protocol)");
}
}
}.start();
}
}, bottomPanel2);
upload.setVisible(files.hasUploadableSites());
enableUploadOrNot();
if (gitVersion != null) {
bottomPanel2.add(Box.createRigidArea(new Dimension(15, 0)));
showChanges =
SwingTools.button("Show changes",
"Show the differences to the uploaded version", new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
for (final FileObject file : table.getSelectedFiles()) try {
final DiffFile diff = new DiffFile(files, file, Mode.LIST_FILES);
diff.setLocationRelativeTo(UpdaterFrame.this);
diff.setVisible(true);
} catch (MalformedURLException e) {
files.log.error(e);
UpdaterUserInterface.get().error("There was a problem obtaining the remote version of " + file.getLocalFilename(true));
}
}
}.start();
}
}, bottomPanel2);
}
final IJ1Plugin rebuild = IJ1Plugin.discover("fiji.scripting.RunFijiBuild");
if (rebuild != null && files.prefix(".git").isDirectory()) {
bottomPanel2.add(Box.createRigidArea(new Dimension(15, 0)));
rebuildButton =
SwingTools.button("Rebuild", "Rebuild using Fiji Build",
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
String list = "";
final List<String> names = new ArrayList<String>();
for (final FileObject file : table.getSelectedFiles()) {
list +=
("".equals(list) ? "" : " ") + file.filename + "-rebuild";
names.add(file.filename);
}
if (!"".equals(list)) rebuild.run(list);
final Checksummer checksummer =
new Checksummer(files,
getProgress("Checksumming rebuilt files"));
checksummer.updateFromLocal(names);
filesChanged();
updateFilesTable();
}
}.start();
}
}, bottomPanel2);
}
bottomPanel2.add(Box.createHorizontalGlue());
bottomPanel.add(Box.createRigidArea(new Dimension(15, 0)));
easy =
SwingTools.button("Toggle easy mode",
"Toggle between easy and verbose mode", new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
toggleEasyMode();
}
}, bottomPanel);
bottomPanel.add(Box.createRigidArea(new Dimension(15, 0)));
cancel =
SwingTools.button("Close", "Exit Update Manager", new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
quit();
}
}, bottomPanel);
// ======== End: BOTTOM PANEL ========
getContentPane().setLayout(
new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(topPanel);
getContentPane().add(summaryPanel);
getContentPane().add(bottomPanel);
getContentPane().add(bottomPanel2);
getRootPane().setDefaultButton(apply);
table.getModel().addTableModelListener(this);
pack();
SwingTools.addAccelerator(cancel, (JComponent) getContentPane(), cancel
.getActionListeners()[0], KeyEvent.VK_ESCAPE, 0);
}
protected static class IJ1Plugin {
protected Object file;
protected Method run;
protected void run(final String arg) {
try {
run.invoke(file, arg);
}
catch (final Exception e) {
UpdaterUserInterface.get().handleException(e);
}
}
protected static IJ1Plugin discover(final String className) {
try {
final IJ1Plugin instance = new IJ1Plugin();
final Class<?> clazz =
IJ1Plugin.class.getClassLoader().loadClass(className);
instance.file = clazz.newInstance();
instance.run = instance.file.getClass().getMethod("run", String.class);
return instance;
}
catch (final Throwable e) {
return null;
}
}
}
@Override
public void setVisible(final boolean visible) {
if (!SwingUtilities.isEventDispatchThread()) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
setVisible(visible);
}
});
} catch (InterruptedException e) {
// ignore
} catch (InvocationTargetException e) {
log.error(e);
}
return;
}
showOrHide();
super.setVisible(visible);
if (visible) {
UpdaterUserInterface.get().addWindow(this);
apply.requestFocusInWindow();
}
}
@Override
public void dispose() {
UpdaterUserInterface.get().removeWindow(this);
super.dispose();
}
public Progress getProgress(final String title) {
return new ProgressDialog(this, title);
}
/**
* Sets the context class loader if necessary.
*
* If the current class cannot be found by the current Thread's context
* class loader, we should tell the Thread about the class loader that
* loaded this class.
*/
private void setClassLoaderIfNecessary() {
ClassLoader thisLoader = getClass().getClassLoader();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
for (; loader != null; loader = loader.getParent()) {
if (thisLoader == loader) return;
}
Thread.currentThread().setContextClassLoader(thisLoader);
}
/** Gets the uploader service associated with this updater frame. */
public UploaderService getUploaderService() {
if (uploaderService == null) {
setClassLoaderIfNecessary();
final Context context = new Context(UploaderService.class);
uploaderService = context.getService(UploaderService.class);
}
return uploaderService;
}
@Override
public void valueChanged(final ListSelectionEvent event) {
filesChanged();
}
List<FileAction> fileActions = new ArrayList<FileAction>();
protected class FileAction extends JButton implements ActionListener {
protected String label, otherLabel;
protected Action action, otherAction;
public FileAction(final String label, final Action action) {
this(label, action, null, null);
}
public FileAction(final String label, final Action action,
final String otherLabel, final Action otherAction)
{
super(label);
this.label = label;
this.action = action;
this.otherLabel = otherLabel;
this.otherAction = otherAction;
addActionListener(this);
fileActions.add(this);
}
@Override
public void actionPerformed(final ActionEvent e) {
if (table.isEditing()) table.editingCanceled(null);
for (final FileObject file : table.getSelectedFiles()) {
if (action == null) file.setNoAction();
else if (!setAction(file)) continue;
table.fireFileChanged(file);
}
filesChanged();
}
protected boolean setAction(final FileObject file) {
return file.setFirstValidAction(files,
new Action[] { action, otherAction });
}
public void enableIfValid() {
boolean enable = false, enableOther = false;
for (final FileObject file : table.getSelectedFiles()) {
final Status status = file.getStatus();
if (action == null) enable = true;
else if (status.isValid(action)) enable = true;
else if (status.isValid(otherAction)) enableOther = true;
if (enable && enableOther) break;
}
setText(!enableOther ? label : (enable ? label + "/" : "") + otherLabel);
setEnabled(enable || enableOther);
}
}
public void addCustomViewOptions() {
viewOptions.clearCustomOptions();
final Collection<String> names = files.getUpdateSiteNames();
if (names.size() > 1) for (final String name : names)
viewOptions.addCustomOption("View files of the '" + name + "' site",
files.forUpdateSite(name));
}
public void setViewOption(final ViewOptions.Option option) {
SwingTools.invokeOnEDT(new Runnable() {
@Override
public void run() {
viewOptions.setSelectedItem(option);
updateFilesTable();
}
});
}
public void updateFilesTable() {
SwingTools.invokeOnEDT(new Runnable() {
@Override
public void run() {
Iterable<FileObject> view = viewOptions.getView(table);
final Set<FileObject> selected = new HashSet<FileObject>();
for (final FileObject file : table.getSelectedFiles())
selected.add(file);
table.clearSelection();
final String search = searchTerm.getText().trim();
if (!search.equals("")) view = FilesCollection.filter(search, view);
// Directly update the table for display
table.setFiles(view);
for (int i = 0; i < table.getRowCount(); i++)
if (selected.contains(table.getFile(i))) table.addRowSelectionInterval(i,
i);
}
});
}
public void applyChanges() {
final ResolveDependencies resolver = new ResolveDependencies(this, files);
if (!resolver.resolve()) return;
new Thread() {
@Override
public void run() {
install();
}
}.start();
}
private void quit() {
if (files.hasChanges()) {
if (!SwingTools.showQuestion(this, "Quit?",
"You have specified changes. Are you sure you want to quit?")) return;
}
else try {
files.write();
}
catch (final Exception e) {
error("There was an error writing the local metadata cache: " + e);
}
dispose();
}
public void setEasyMode(final boolean easyMode) {
this.easyMode = easyMode;
showOrHide();
if (isVisible()) repaint();
}
protected void showOrHide() {
for (final FileAction action : fileActions) {
action.setVisible(!easyMode);
}
searchPanel.setVisible(!easyMode);
viewOptionsPanel.setVisible(!easyMode);
chooseLabel.setVisible(!easyMode);
summaryPanel.setVisible(!easyMode);
rightPanel.setVisible(!easyMode);
updateSites.setVisible(!easyMode);
final boolean uploadable = !easyMode && files.hasUploadableSites();
upload.setVisible(uploadable);
if (showChanges != null) showChanges.setVisible(!easyMode && gitVersion != null);
if (rebuildButton != null) rebuildButton.setVisible(uploadable);
easy.setText(easyMode ? "Advanced mode" : "Easy mode");
}
public void toggleEasyMode() {
setEasyMode(!easyMode);
}
public void install() {
final Installer installer =
new Installer(files, getProgress("Installing..."));
try {
installer.start();
updateFilesTable();
filesChanged();
files.write();
info("Updated successfully. Please restart ImageJ!");
dispose();
}
catch (final UpdateCanceledException e) {
// TODO: remove "update/" directory
error("Canceled");
installer.done();
}
catch (final Exception e) {
log.error(e);
// TODO: remove "update/" directory
error("Installer failed: " + e);
installer.done();
}
}
private Thread filesChangedWorker;
public synchronized void filesChanged() {
if (filesChangedWorker != null) return;
filesChangedWorker = new Thread() {
@Override
public void run() {
filesChangedWorker();
synchronized (UpdaterFrame.this) {
filesChangedWorker = null;
}
}
};
SwingUtilities.invokeLater(filesChangedWorker);
}
private void filesChangedWorker() {
// TODO: once this is editable, make sure changes are committed
fileDetails.reset();
for (final FileObject file : table.getSelectedFiles())
fileDetails.showFileDetails(file);
if (fileDetails.getDocument().getLength() > 0 &&
table.areAllSelectedFilesUploadable()) fileDetails
.setEditableForDevelopers();
for (final FileAction button : fileActions)
button.enableIfValid();
if (showChanges != null) showChanges.setEnabled(table.getSelectedFiles().iterator().hasNext());
apply.setEnabled(files.hasChanges());
cancel.setText(files.hasChanges() ? "Cancel" : "Close");
if (files.hasUploadableSites()) enableUploadOrNot();
int install = 0, uninstall = 0, upload = 0;
long bytesToDownload = 0, bytesToUpload = 0;
for (final FileObject file : files)
switch (file.getAction()) {
case INSTALL:
case UPDATE:
install++;
bytesToDownload += file.filesize;
break;
case UNINSTALL:
uninstall++;
break;
case UPLOAD:
upload++;
bytesToUpload += file.filesize;
break;
default:
}
int implicated = 0;
final DependencyMap map = files.getDependencies(true);
for (final FileObject file : map.keySet()) {
implicated++;
bytesToUpload += file.filesize;
}
String text = "";
if (install > 0) text +=
" install/update: " + install + (implicated > 0 ? "+" + implicated : "") +
" (" + sizeToString(bytesToDownload) + ")";
if (uninstall > 0) text += " uninstall: " + uninstall;
if (files.hasUploadableSites() && upload > 0) text +=
" upload: " + upload + " (" + sizeToString(bytesToUpload) + ")";
fileSummary.setText(text);
}
protected final static String[] units = { "B", "kB", "MB", "GB", "TB" };
public static String sizeToString(long size) {
int i;
for (i = 1; i < units.length && size >= 1l << (10 * i); i++); // do nothing
if (--i == 0) return "" + size + units[i];
// round
size *= 100;
size >>= (10 * i);
size += 5;
size /= 10;
return "" + (size / 10) + "." + (size % 10) + units[i];
}
@Override
public void tableChanged(final TableModelEvent e) {
filesChanged();
}
// checkWritable() is guaranteed to be called after Checksummer ran
public void checkWritable() {
String list = null;
for (final FileObject object : files) {
final File file = files.prefix(object);
if (!file.exists() || file.canWrite()) continue;
if (list == null) list = object.getFilename();
else list += ", " + object.getFilename();
}
if (list != null) UpdaterUserInterface.get().info(
"WARNING: The following files are set to read-only: '" + list + "'",
"Read-only files");
}
void markUploadable() {
canUpload = true;
enableUploadOrNot();
}
void enableUploadOrNot() {
upload.setVisible(!easyMode && files.hasUploadableSites());
upload.setEnabled(canUpload || files.hasUploadOrRemove());
}
protected void upload() throws InstantiationException {
final ResolveDependencies resolver =
new ResolveDependencies(this, files, true);
if (!resolver.resolve()) return;
final String errors = files.checkConsistency();
if (errors != null) {
error(errors);
return;
}
final List<String> possibleSites =
new ArrayList<String>(files.getSiteNamesToUpload());
if (possibleSites.size() == 0) {
error("Huh? No upload site?");
return;
}
String updateSiteName;
if (possibleSites.size() == 1) updateSiteName = possibleSites.get(0);
else {
updateSiteName =
SwingTools.getChoice(this, possibleSites,
"Which site do you want to upload to?", "Update site");
if (updateSiteName == null) return;
}
final FilesUploader uploader = new FilesUploader(uploaderService, files, updateSiteName, getProgress(null));
Progress progress = null;
try {
if (!uploader.login()) return;
progress = getProgress("Uploading...");
uploader.upload(progress);
for (final FileObject file : files.toUploadOrRemove())
if (file.getAction() == Action.UPLOAD) {
file.markUploaded();
file.setStatus(Status.INSTALLED);
}
else {
file.markRemoved();
file.setStatus(Status.OBSOLETE_UNINSTALLED);
}
updateFilesTable();
canUpload = false;
files.write();
info("Uploaded successfully.");
enableUploadOrNot();
dispose();
}
catch (final UpdateCanceledException e) {
// TODO: teach uploader to remove the lock file
error("Canceled");
if (progress != null) progress.done();
}
catch (final Throwable e) {
UpdaterUserInterface.get().handleException(e);
error("Upload failed: " + e);
if (progress != null) progress.done();
}
}
protected boolean initializeUpdateSite(final String url,
final String sshHost, final String uploadDirectory)
throws InstantiationException
{
final FilesUploader uploader =
FilesUploader.initialUploader(uploaderService, url, sshHost, uploadDirectory, getProgress(null));
Progress progress = null;
try {
if (!uploader.login()) return false;
progress = getProgress("Initializing Update Site...");
uploader.upload(progress);
// JSch needs some time to finalize the SSH connection
try {
Thread.sleep(1000);
}
catch (final InterruptedException e) { /* ignore */}
return true;
}
catch (final UpdateCanceledException e) {
if (progress != null) progress.done();
}
catch (final Throwable e) {
UpdaterUserInterface.get().handleException(e);
if (progress != null) progress.done();
}
return false;
}
public void error(final String message) {
SwingTools.showMessageBox(this, message, JOptionPane.ERROR_MESSAGE);
}
public void warn(final String message) {
SwingTools.showMessageBox(this, message, JOptionPane.WARNING_MESSAGE);
}
public void info(final String message) {
SwingTools.showMessageBox(this, message, JOptionPane.INFORMATION_MESSAGE);
}
}
| ui/swing/updater/src/main/java/imagej/updater/gui/UpdaterFrame.java | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2013 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.updater.gui;
import imagej.updater.core.Checksummer;
import imagej.updater.core.Diff.Mode;
import imagej.updater.core.FileObject;
import imagej.updater.core.FileObject.Action;
import imagej.updater.core.FileObject.Status;
import imagej.updater.core.FilesCollection;
import imagej.updater.core.FilesCollection.DependencyMap;
import imagej.updater.core.FilesUploader;
import imagej.updater.core.Installer;
import imagej.updater.core.UploaderService;
import imagej.updater.util.Progress;
import imagej.updater.util.UpdateCanceledException;
import imagej.updater.util.UpdaterUserInterface;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.scijava.Context;
import org.scijava.log.LogService;
import org.scijava.util.ProcessUtils;
/**
* TODO
*
* @author Johannes Schindelin
*/
@SuppressWarnings("serial")
public class UpdaterFrame extends JFrame implements TableModelListener,
ListSelectionListener
{
protected LogService log;
private UploaderService uploaderService;
protected FilesCollection files;
protected JTextField searchTerm;
protected JPanel searchPanel;
protected ViewOptions viewOptions;
protected JPanel viewOptionsPanel;
protected JPanel chooseLabel;
protected FileTable table;
protected JLabel fileSummary;
protected JPanel summaryPanel;
protected JPanel rightPanel;
protected FileDetails fileDetails;
protected JButton apply, cancel, easy, updateSites;
protected boolean easyMode;
// For developers
protected JButton upload, showChanges, rebuildButton;
protected boolean canUpload;
protected final static String gitVersion;
static {
String version = null;
try {
version = ProcessUtils.exec(null, null, null, "git", "--version");
} catch (Throwable t) { /* ignore */ }
gitVersion = version;
}
public UpdaterFrame(final LogService log,
final UploaderService uploaderService, final FilesCollection files)
{
super("ImageJ Updater");
setPreferredSize(new Dimension(780, 560));
this.log = log;
this.uploaderService = uploaderService;
this.files = files;
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
quit();
}
});
// ======== Start: LEFT PANEL ========
final JPanel leftPanel = new JPanel();
final GridBagLayout gb = new GridBagLayout();
leftPanel.setLayout(gb);
final GridBagConstraints c = new GridBagConstraints(0, 0, // x, y
9, 1, // rows, cols
0, 0, // weightx, weighty
GridBagConstraints.NORTHWEST, // anchor
GridBagConstraints.HORIZONTAL, // fill
new Insets(0, 0, 0, 0), 0, 0); // ipadx, ipady
searchTerm = new JTextField();
searchTerm.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(final DocumentEvent e) {
updateFilesTable();
}
@Override
public void removeUpdate(final DocumentEvent e) {
updateFilesTable();
}
@Override
public void insertUpdate(final DocumentEvent e) {
updateFilesTable();
}
});
searchPanel = SwingTools.labelComponentRigid("Search:", searchTerm);
gb.setConstraints(searchPanel, c);
leftPanel.add(searchPanel);
Component box = Box.createRigidArea(new Dimension(0, 10));
c.gridy = 1;
gb.setConstraints(box, c);
leftPanel.add(box);
viewOptions = new ViewOptions();
viewOptions.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
updateFilesTable();
}
});
viewOptionsPanel =
SwingTools.labelComponentRigid("View Options:", viewOptions);
c.gridy = 2;
gb.setConstraints(viewOptionsPanel, c);
leftPanel.add(viewOptionsPanel);
box = Box.createRigidArea(new Dimension(0, 10));
c.gridy = 3;
gb.setConstraints(box, c);
leftPanel.add(box);
// Create labels to annotate table
chooseLabel =
SwingTools.label("Please choose what you want to install/uninstall:",
null);
c.gridy = 4;
gb.setConstraints(chooseLabel, c);
leftPanel.add(chooseLabel);
box = Box.createRigidArea(new Dimension(0, 5));
c.gridy = 5;
gb.setConstraints(box, c);
leftPanel.add(box);
// Label text for file summaries
fileSummary = new JLabel();
summaryPanel = SwingTools.horizontalPanel();
summaryPanel.add(fileSummary);
summaryPanel.add(Box.createHorizontalGlue());
// Create the file table and set up its scrollpane
table = new FileTable(this);
table.getSelectionModel().addListSelectionListener(this);
final JScrollPane fileListScrollpane = new JScrollPane(table);
fileListScrollpane.getViewport().setBackground(table.getBackground());
c.gridy = 6;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
gb.setConstraints(fileListScrollpane, c);
leftPanel.add(fileListScrollpane);
box = Box.createRigidArea(new Dimension(0, 5));
c.gridy = 7;
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
gb.setConstraints(box, c);
leftPanel.add(box);
// ======== End: LEFT PANEL ========
// ======== Start: RIGHT PANEL ========
rightPanel = SwingTools.verticalPanel();
rightPanel.add(Box.createVerticalGlue());
fileDetails = new FileDetails(this);
SwingTools.tab(fileDetails, "Details", "Individual file information", 350,
315, rightPanel);
// TODO: put this into SwingTools, too
rightPanel.add(Box.createRigidArea(new Dimension(0, 25)));
// ======== End: RIGHT PANEL ========
// ======== Start: TOP PANEL (LEFT + RIGHT) ========
final JPanel topPanel = SwingTools.horizontalPanel();
topPanel.add(leftPanel);
topPanel.add(Box.createRigidArea(new Dimension(15, 0)));
topPanel.add(rightPanel);
topPanel.setBorder(BorderFactory.createEmptyBorder(20, 15, 5, 15));
// ======== End: TOP PANEL (LEFT + RIGHT) ========
// ======== Start: BOTTOM PANEL ========
final JPanel bottomPanel2 = SwingTools.horizontalPanel();
final JPanel bottomPanel = SwingTools.horizontalPanel();
bottomPanel.setBorder(BorderFactory.createEmptyBorder(5, 15, 15, 15));
bottomPanel.add(new FileAction("Keep as-is", null));
bottomPanel.add(Box.createRigidArea(new Dimension(15, 0)));
bottomPanel.add(new FileAction("Install", Action.INSTALL, "Update",
Action.UPDATE));
bottomPanel.add(Box.createRigidArea(new Dimension(15, 0)));
bottomPanel.add(new FileAction("Uninstall", Action.UNINSTALL));
bottomPanel.add(Box.createHorizontalGlue());
// make sure that sezpoz finds the classes when triggered from the EDT
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
SwingTools.invokeOnEDT(new Runnable() {
@Override
public void run() {
if (contextClassLoader != null)
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
});
// Button to start actions
apply =
SwingTools.button("Apply changes", "Start installing/uninstalling files",
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
applyChanges();
}
}, bottomPanel);
apply.setEnabled(files.hasChanges());
// Manage update sites
updateSites =
SwingTools.button("Manage update sites",
"Manage multiple update sites for updating and uploading",
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
new SitesDialog(UpdaterFrame.this, UpdaterFrame.this.files).setVisible(true);
}
}, bottomPanel2);
// TODO: unify upload & apply changes (probably apply changes first, then
// upload)
// includes button to upload to server if is a Developer using
bottomPanel2.add(Box.createRigidArea(new Dimension(15, 0)));
upload =
SwingTools.button("Upload to server", "Upload selected files to server",
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
try {
upload();
}
catch (final InstantiationException e) {
log.error(e);
error("Could not upload (possibly unknown protocol)");
}
}
}.start();
}
}, bottomPanel2);
upload.setVisible(files.hasUploadableSites());
enableUploadOrNot();
if (gitVersion != null) {
bottomPanel2.add(Box.createRigidArea(new Dimension(15, 0)));
showChanges =
SwingTools.button("Show changes",
"Show the differences to the uploaded version", new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
for (final FileObject file : table.getSelectedFiles()) try {
final DiffFile diff = new DiffFile(files, file, Mode.LIST_FILES);
diff.setLocationRelativeTo(UpdaterFrame.this);
diff.setVisible(true);
} catch (MalformedURLException e) {
files.log.error(e);
UpdaterUserInterface.get().error("There was a problem obtaining the remote version of " + file.getLocalFilename(true));
}
}
}.start();
}
}, bottomPanel2);
}
final IJ1Plugin rebuild = IJ1Plugin.discover("fiji.scripting.RunFijiBuild");
if (rebuild != null && files.prefix(".git").isDirectory()) {
bottomPanel2.add(Box.createRigidArea(new Dimension(15, 0)));
rebuildButton =
SwingTools.button("Rebuild", "Rebuild using Fiji Build",
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
new Thread() {
@Override
public void run() {
String list = "";
final List<String> names = new ArrayList<String>();
for (final FileObject file : table.getSelectedFiles()) {
list +=
("".equals(list) ? "" : " ") + file.filename + "-rebuild";
names.add(file.filename);
}
if (!"".equals(list)) rebuild.run(list);
final Checksummer checksummer =
new Checksummer(files,
getProgress("Checksumming rebuilt files"));
checksummer.updateFromLocal(names);
filesChanged();
updateFilesTable();
}
}.start();
}
}, bottomPanel2);
}
bottomPanel2.add(Box.createHorizontalGlue());
bottomPanel.add(Box.createRigidArea(new Dimension(15, 0)));
easy =
SwingTools.button("Toggle easy mode",
"Toggle between easy and verbose mode", new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
toggleEasyMode();
}
}, bottomPanel);
bottomPanel.add(Box.createRigidArea(new Dimension(15, 0)));
cancel =
SwingTools.button("Close", "Exit Update Manager", new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
quit();
}
}, bottomPanel);
// ======== End: BOTTOM PANEL ========
getContentPane().setLayout(
new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(topPanel);
getContentPane().add(summaryPanel);
getContentPane().add(bottomPanel);
getContentPane().add(bottomPanel2);
getRootPane().setDefaultButton(apply);
table.getModel().addTableModelListener(this);
pack();
SwingTools.addAccelerator(cancel, (JComponent) getContentPane(), cancel
.getActionListeners()[0], KeyEvent.VK_ESCAPE, 0);
}
protected static class IJ1Plugin {
protected Object file;
protected Method run;
protected void run(final String arg) {
try {
run.invoke(file, arg);
}
catch (final Exception e) {
UpdaterUserInterface.get().handleException(e);
}
}
protected static IJ1Plugin discover(final String className) {
try {
final IJ1Plugin instance = new IJ1Plugin();
final Class<?> clazz =
IJ1Plugin.class.getClassLoader().loadClass(className);
instance.file = clazz.newInstance();
instance.run = instance.file.getClass().getMethod("run", String.class);
return instance;
}
catch (final Throwable e) {
return null;
}
}
}
@Override
public void setVisible(final boolean visible) {
if (!SwingUtilities.isEventDispatchThread()) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
setVisible(visible);
}
});
} catch (InterruptedException e) {
// ignore
} catch (InvocationTargetException e) {
log.error(e);
}
return;
}
showOrHide();
super.setVisible(visible);
if (visible) {
UpdaterUserInterface.get().addWindow(this);
apply.requestFocusInWindow();
}
}
@Override
public void dispose() {
UpdaterUserInterface.get().removeWindow(this);
super.dispose();
}
public Progress getProgress(final String title) {
return new ProgressDialog(this, title);
}
/**
* Sets the context class loader if necessary.
*
* If the current class cannot be found by the current Thread's context
* class loader, we should tell the Thread about the class loader that
* loaded this class.
*/
private void setClassLoaderIfNecessary() {
ClassLoader thisLoader = getClass().getClassLoader();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
for (; loader != null; loader = loader.getParent()) {
if (thisLoader == loader) return;
}
Thread.currentThread().setContextClassLoader(thisLoader);
}
/** Gets the uploader service associated with this updater frame. */
public UploaderService getUploaderService() {
if (uploaderService == null) {
setClassLoaderIfNecessary();
final Context context = new Context(UploaderService.class);
uploaderService = context.getService(UploaderService.class);
}
return uploaderService;
}
@Override
public void valueChanged(final ListSelectionEvent event) {
filesChanged();
}
List<FileAction> fileActions = new ArrayList<FileAction>();
protected class FileAction extends JButton implements ActionListener {
protected String label, otherLabel;
protected Action action, otherAction;
public FileAction(final String label, final Action action) {
this(label, action, null, null);
}
public FileAction(final String label, final Action action,
final String otherLabel, final Action otherAction)
{
super(label);
this.label = label;
this.action = action;
this.otherLabel = otherLabel;
this.otherAction = otherAction;
addActionListener(this);
fileActions.add(this);
}
@Override
public void actionPerformed(final ActionEvent e) {
if (table.isEditing()) table.editingCanceled(null);
for (final FileObject file : table.getSelectedFiles()) {
if (action == null) file.setNoAction();
else if (!setAction(file)) continue;
table.fireFileChanged(file);
}
filesChanged();
}
protected boolean setAction(final FileObject file) {
return file.setFirstValidAction(files,
new Action[] { action, otherAction });
}
public void enableIfValid() {
boolean enable = false, enableOther = false;
for (final FileObject file : table.getSelectedFiles()) {
final Status status = file.getStatus();
if (action == null) enable = true;
else if (status.isValid(action)) enable = true;
else if (status.isValid(otherAction)) enableOther = true;
if (enable && enableOther) break;
}
setText(!enableOther ? label : (enable ? label + "/" : "") + otherLabel);
setEnabled(enable || enableOther);
}
}
public void addCustomViewOptions() {
viewOptions.clearCustomOptions();
final Collection<String> names = files.getUpdateSiteNames();
if (names.size() > 1) for (final String name : names)
viewOptions.addCustomOption("View files of the '" + name + "' site",
files.forUpdateSite(name));
}
public void setViewOption(final ViewOptions.Option option) {
SwingTools.invokeOnEDT(new Runnable() {
@Override
public void run() {
viewOptions.setSelectedItem(option);
updateFilesTable();
}
});
}
public void updateFilesTable() {
SwingTools.invokeOnEDT(new Runnable() {
@Override
public void run() {
Iterable<FileObject> view = viewOptions.getView(table);
final Set<FileObject> selected = new HashSet<FileObject>();
for (final FileObject file : table.getSelectedFiles())
selected.add(file);
table.clearSelection();
final String search = searchTerm.getText().trim();
if (!search.equals("")) view = FilesCollection.filter(search, view);
// Directly update the table for display
table.setFiles(view);
for (int i = 0; i < table.getRowCount(); i++)
if (selected.contains(table.getFile(i))) table.addRowSelectionInterval(i,
i);
}
});
}
public void applyChanges() {
final ResolveDependencies resolver = new ResolveDependencies(this, files);
if (!resolver.resolve()) return;
new Thread() {
@Override
public void run() {
install();
}
}.start();
}
private void quit() {
if (files.hasChanges()) {
if (!SwingTools.showQuestion(this, "Quit?",
"You have specified changes. Are you sure you want to quit?")) return;
}
else try {
files.write();
}
catch (final Exception e) {
error("There was an error writing the local metadata cache: " + e);
}
dispose();
}
public void setEasyMode(final boolean easyMode) {
this.easyMode = easyMode;
showOrHide();
if (isVisible()) repaint();
}
protected void showOrHide() {
for (final FileAction action : fileActions) {
action.setVisible(!easyMode);
}
searchPanel.setVisible(!easyMode);
viewOptionsPanel.setVisible(!easyMode);
chooseLabel.setVisible(!easyMode);
summaryPanel.setVisible(!easyMode);
rightPanel.setVisible(!easyMode);
updateSites.setVisible(!easyMode);
final boolean uploadable = !easyMode && files.hasUploadableSites();
upload.setVisible(uploadable);
if (showChanges != null) showChanges.setVisible(!easyMode && gitVersion != null);
if (rebuildButton != null) rebuildButton.setVisible(uploadable);
easy.setText(easyMode ? "Advanced mode" : "Easy mode");
}
public void toggleEasyMode() {
setEasyMode(!easyMode);
}
public void install() {
final Installer installer =
new Installer(files, getProgress("Installing..."));
try {
installer.start();
updateFilesTable();
filesChanged();
files.write();
info("Updated successfully. Please restart ImageJ!");
dispose();
}
catch (final UpdateCanceledException e) {
// TODO: remove "update/" directory
error("Canceled");
installer.done();
}
catch (final Exception e) {
log.error(e);
// TODO: remove "update/" directory
error("Installer failed: " + e);
installer.done();
}
}
private Thread filesChangedWorker;
public synchronized void filesChanged() {
if (filesChangedWorker != null) return;
filesChangedWorker = new Thread() {
@Override
public void run() {
filesChangedWorker();
synchronized (UpdaterFrame.this) {
filesChangedWorker = null;
}
}
};
SwingUtilities.invokeLater(filesChangedWorker);
}
private void filesChangedWorker() {
// TODO: once this is editable, make sure changes are committed
fileDetails.reset();
for (final FileObject file : table.getSelectedFiles())
fileDetails.showFileDetails(file);
if (fileDetails.getDocument().getLength() > 0 &&
table.areAllSelectedFilesUploadable()) fileDetails
.setEditableForDevelopers();
for (final FileAction button : fileActions)
button.enableIfValid();
if (showChanges != null) showChanges.setEnabled(table.getSelectedFiles().iterator().hasNext());
apply.setEnabled(files.hasChanges());
cancel.setText(files.hasChanges() ? "Cancel" : "Close");
if (files.hasUploadableSites()) enableUploadOrNot();
int install = 0, uninstall = 0, upload = 0;
long bytesToDownload = 0, bytesToUpload = 0;
for (final FileObject file : files)
switch (file.getAction()) {
case INSTALL:
case UPDATE:
install++;
bytesToDownload += file.filesize;
break;
case UNINSTALL:
uninstall++;
break;
case UPLOAD:
upload++;
bytesToUpload += file.filesize;
break;
}
int implicated = 0;
final DependencyMap map = files.getDependencies(true);
for (final FileObject file : map.keySet()) {
implicated++;
bytesToUpload += file.filesize;
}
String text = "";
if (install > 0) text +=
" install/update: " + install + (implicated > 0 ? "+" + implicated : "") +
" (" + sizeToString(bytesToDownload) + ")";
if (uninstall > 0) text += " uninstall: " + uninstall;
if (files.hasUploadableSites() && upload > 0) text +=
" upload: " + upload + " (" + sizeToString(bytesToUpload) + ")";
fileSummary.setText(text);
}
protected final static String[] units = { "B", "kB", "MB", "GB", "TB" };
public static String sizeToString(long size) {
int i;
for (i = 1; i < units.length && size >= 1l << (10 * i); i++); // do nothing
if (--i == 0) return "" + size + units[i];
// round
size *= 100;
size >>= (10 * i);
size += 5;
size /= 10;
return "" + (size / 10) + "." + (size % 10) + units[i];
}
@Override
public void tableChanged(final TableModelEvent e) {
filesChanged();
}
// checkWritable() is guaranteed to be called after Checksummer ran
public void checkWritable() {
String list = null;
for (final FileObject object : files) {
final File file = files.prefix(object);
if (!file.exists() || file.canWrite()) continue;
if (list == null) list = object.getFilename();
else list += ", " + object.getFilename();
}
if (list != null) UpdaterUserInterface.get().info(
"WARNING: The following files are set to read-only: '" + list + "'",
"Read-only files");
}
void markUploadable() {
canUpload = true;
enableUploadOrNot();
}
void enableUploadOrNot() {
upload.setVisible(!easyMode && files.hasUploadableSites());
upload.setEnabled(canUpload || files.hasUploadOrRemove());
}
protected void upload() throws InstantiationException {
final ResolveDependencies resolver =
new ResolveDependencies(this, files, true);
if (!resolver.resolve()) return;
final String errors = files.checkConsistency();
if (errors != null) {
error(errors);
return;
}
final List<String> possibleSites =
new ArrayList<String>(files.getSiteNamesToUpload());
if (possibleSites.size() == 0) {
error("Huh? No upload site?");
return;
}
String updateSiteName;
if (possibleSites.size() == 1) updateSiteName = possibleSites.get(0);
else {
updateSiteName =
SwingTools.getChoice(this, possibleSites,
"Which site do you want to upload to?", "Update site");
if (updateSiteName == null) return;
}
final FilesUploader uploader = new FilesUploader(uploaderService, files, updateSiteName, getProgress(null));
Progress progress = null;
try {
if (!uploader.login()) return;
progress = getProgress("Uploading...");
uploader.upload(progress);
for (final FileObject file : files.toUploadOrRemove())
if (file.getAction() == Action.UPLOAD) {
file.markUploaded();
file.setStatus(Status.INSTALLED);
}
else {
file.markRemoved();
file.setStatus(Status.OBSOLETE_UNINSTALLED);
}
updateFilesTable();
canUpload = false;
files.write();
info("Uploaded successfully.");
enableUploadOrNot();
dispose();
}
catch (final UpdateCanceledException e) {
// TODO: teach uploader to remove the lock file
error("Canceled");
if (progress != null) progress.done();
}
catch (final Throwable e) {
UpdaterUserInterface.get().handleException(e);
error("Upload failed: " + e);
if (progress != null) progress.done();
}
}
protected boolean initializeUpdateSite(final String url,
final String sshHost, final String uploadDirectory)
throws InstantiationException
{
final FilesUploader uploader =
FilesUploader.initialUploader(uploaderService, url, sshHost, uploadDirectory, getProgress(null));
Progress progress = null;
try {
if (!uploader.login()) return false;
progress = getProgress("Initializing Update Site...");
uploader.upload(progress);
// JSch needs some time to finalize the SSH connection
try {
Thread.sleep(1000);
}
catch (final InterruptedException e) { /* ignore */}
return true;
}
catch (final UpdateCanceledException e) {
if (progress != null) progress.done();
}
catch (final Throwable e) {
UpdaterUserInterface.get().handleException(e);
if (progress != null) progress.done();
}
return false;
}
public void error(final String message) {
SwingTools.showMessageBox(this, message, JOptionPane.ERROR_MESSAGE);
}
public void warn(final String message) {
SwingTools.showMessageBox(this, message, JOptionPane.WARNING_MESSAGE);
}
public void info(final String message) {
SwingTools.showMessageBox(this, message, JOptionPane.INFORMATION_MESSAGE);
}
}
| Updater (Swing): fix compiler warning
Signed-off-by: Johannes Schindelin <[email protected]>
| ui/swing/updater/src/main/java/imagej/updater/gui/UpdaterFrame.java | Updater (Swing): fix compiler warning |
|
Java | bsd-3-clause | d23ac546d3cbc877f67533a8746770dc7b652395 | 0 | Adam5Wu/ZWUtils-Java,Adam5Wu/ZWUtils-Java,Adam5Wu/ZWUtils-Java | // NEC Labs America Inc. CONFIDENTIAL
package com.necla.am.zwutils;
import com.necla.am.zwutils.Misc.Versioning;
public class _Namespace {
public static final String PRODUCT = "ZWUtils - Jack of All Trades Utility Libraries";
public static final String COMPONENT = "ZWUtils for Java";
public static final String VERSION = "@VERSION@".toString();
public static final String BUILD = "@DATE@ @TIME@".toString();
static {
Versioning.Namespace_Init(_Namespace.class);
}
}
| main/src/java/com/necla/am/zwutils/_Namespace.java | // NEC Labs America Inc. CONFIDENTIAL
package com.necla.am.zwutils;
import com.necla.am.zwutils.Misc.Versioning;
public class _Namespace {
public static final String PRODUCT = "ZWUtils - Jack of All Trades Utility Libraries";
public static final String COMPONENT = "ZWUtils for Java";
public static final String VERSION = "@VERSION@";
public static final String BUILD = "@DATE@ @TIME@";
static {
Versioning.Namespace_Init(_Namespace.class);
}
}
| Improve namespace programmatic access in Eclipse debug mode
| main/src/java/com/necla/am/zwutils/_Namespace.java | Improve namespace programmatic access in Eclipse debug mode |
|
Java | bsd-3-clause | ae33345898c9520055116d373b399198dfe82f3d | 0 | nesl/sos-2x,nesl/sos-2x,nesl/sos-2x,nesl/sos-2x,nesl/sos-2x,nesl/sos-2x,nesl/sos-2x,nesl/sos-2x | /**
* @file SOSCrashMonitor.java
* @brief Detailed crash report of SOS when it crashes
* @author Ram Kumar {[email protected]}
*/
package sos.monitor;
import avrora.monitors.Monitor;
import avrora.monitors.MonitorFactory;
import avrora.sim.Simulator;
import avrora.sim.State;
import avrora.core.Program;
import avrora.arch.AbstractInstr;
import avrora.arch.legacy.*;
import cck.util.Option;
import cck.util.Util;
import cck.text.TermUtil;
import cck.text.Terminal;
import cck.text.StringUtil;
import java.util.*;
public class SOSCrashMonitor extends MonitorFactory {
public final Option.Long CRASHADDR = options.newOption("crash-addr", 0, "Specify byte address of crash site.");
public final Option.Bool PROFBEFORE = options.newOption("profie-before-fire", false, "Profile before executing an instruction.");
public final Option.Long SFIEXCEPTIONADDR = options.newOption("sfi-exception-addr", 0, "Specify byte address of crash site.");
public final Option.Long TRACELEN = options.newOption("trace-len", 100, "Specify length of intr. trace");
public final Option.Long MEMMAPADDR = options.newOption("memmap-addr", 0, "Specify length of intr. trace");
public final Option.Long MALLOCADDR = options.newOption("malloc-addr", 0, "Specify length of intr. trace");
public final Option.Long FREEADDR = options.newOption("free-addr", 0, "Specify length of intr. trace");
public final Option.Long CHOWNADDR = options.newOption("chown-addr", 0, "Specify length of intr. trace");
public final Option.Long VMPOST = options.newOption("vm-post", 0, "Specify length of intr. trace");
public class Mon implements avrora.monitors.Monitor {
public final Simulator simulator;
public int tracelen;
public int tracePtr;
public int[] tracePC;
public int[] traceSP;
public int[] traceR0;
public int[] traceR1;
public int[] traceR26;
public int[] traceR27;
public int[] traceR30;
public int[] traceR31;
public int memmap_addr;
public int mallocaddr, freeaddr, chownaddr;
public boolean profilebefore;
Mon(Simulator s) {
simulator = s;
tracePtr = 0;
tracelen = (int)TRACELEN.get();
tracePC = new int[tracelen];
traceSP = new int[tracelen];
traceR0 = new int[tracelen];
traceR1 = new int[tracelen];
traceR26 = new int[tracelen];
traceR27 = new int[tracelen];
traceR30 = new int[tracelen];
traceR31 = new int[tracelen];
memmap_addr = (int)MEMMAPADDR.get();
int crashaddr = (int)CRASHADDR.get();
if (crashaddr != 0)
s.insertProbe(new SOSCrashProbe(), crashaddr);
int sfiexceptionaddr = (int)SFIEXCEPTIONADDR.get();
if (sfiexceptionaddr != 0)
s.insertProbe(new SOSSFIExceptionProbe(), sfiexceptionaddr);
mallocaddr = (int)MALLOCADDR.get();
if (mallocaddr != 0)
s.insertProbe(new SOSMemoryMapProbe(), mallocaddr);
freeaddr = (int)FREEADDR.get();
if (freeaddr != 0)
s.insertProbe(new SOSMemoryMapProbe(), freeaddr);
chownaddr = (int)CHOWNADDR.get();
if (chownaddr != 0)
s.insertProbe(new SOSMemoryMapProbe(), chownaddr);
int vmpost = (int)VMPOST.get();
if (vmpost != 0)
s.insertProbe(new SOSDVMProbe(), vmpost);
profilebefore = (boolean)PROFBEFORE.get();
s.insertProbe(new SOSTraceProbe());
}
public class SOSDVMProbe implements Simulator.Probe {
public void fireAfter(State state, int pc){
Simulator simul;
LegacyState legacystate = (LegacyState)state;
int did = legacystate.getRegisterUnsigned(LegacyRegister.R24);
int sid = legacystate.getRegisterUnsigned(LegacyRegister.R22);
int type = legacystate.getRegisterUnsigned(LegacyRegister.R20);
int len = legacystate.getRegisterUnsigned(LegacyRegister.R18);
TermUtil.printSeparator(Terminal.MAXLINE, "DVM POST");
TermUtil.reportQuantity("did: ", StringUtil.addrToString(did), " ");
TermUtil.reportQuantity("sid: ", StringUtil.addrToString(sid), " ");
TermUtil.reportQuantity("type: ", StringUtil.addrToString(type), " ");
TermUtil.reportQuantity("len: ", StringUtil.addrToString(len), " ");
simul = state.getSimulator();
simul.stop();
}
public void fireBefore(State state, int pc){
return;
}
}
public class SOSMemoryMapProbe implements Simulator.Probe {
public void fireAfter(State state, int pc){
LegacyState legacystate = (LegacyState)state;
if (pc == mallocaddr)
Terminal.println("Malloc");
if (pc == freeaddr)
Terminal.println("Free");
if (pc == chownaddr)
Terminal.println("Msg Take Data");
printMemoryMap(legacystate);
}
public void fireBefore(State state, int pc){
return;
}
}
public class SOSSFIExceptionProbe implements Simulator.Probe {
private final int SFI_HEAP_EXCEPTION = 3;
public void fireBefore(State state, int pc){
Simulator simul;
LegacyState legacystate = (LegacyState)state;
int regval = legacystate.getRegisterByte(LegacyRegister.R24);
simul = state.getSimulator();
TermUtil.printSeparator(Terminal.MAXLINE, "SFI Exception");
TermUtil.reportQuantity("Addr: ", StringUtil.addrToString(pc), " ");
TermUtil.reportQuantity("Cycles: ", state.getCycles(), " ");
TermUtil.reportQuantity("Stack: ", StringUtil.addrToString(state.getSP()), " ");
TermUtil.reportQuantity("Excpetion Code (R24): ", StringUtil.addrToString(regval), " ");
printExecTrace(simul);
if (regval == SFI_HEAP_EXCEPTION)
printMemoryMap(legacystate);
simul.stop();
}
public void fireAfter(State state, int pc){
return;
}
}
public class SOSCrashProbe implements Simulator.Probe {
public void fireBefore(State state, int pc){
TermUtil.printSeparator(Terminal.MAXLINE, "Crash Dump");
TermUtil.reportQuantity("Addr: ", StringUtil.addrToString(pc), " ");
TermUtil.reportQuantity("Cycles: ", state.getCycles(), " ");
TermUtil.reportQuantity("Stack: ", StringUtil.addrToString(state.getSP()), " ");
printExecTrace(state.getSimulator());
return;
}
public void fireAfter(State state, int pc){
return;
}
}
public class SOSTraceProbe implements Simulator.Probe{
public void fireBefore(State state, int pc){
/*
LegacyState legacystate = (LegacyState)state;
if (pc == 0xDF44){
Terminal.print("PC: ");
Terminal.print(StringUtil.addrToString(pc));
Terminal.nextln();
Terminal.print(StringUtil.addrToString(legacystate.getProgramByte(pc)));
Terminal.nextln();
Terminal.print(StringUtil.addrToString(legacystate.getProgramByte(pc+1)));
Terminal.nextln();
}
*/
if (profilebefore)
doSOSProfile(state, pc);
return;
}
public void fireAfter(State state, int pc){
if (!profilebefore)
doSOSProfile(state, pc);
return;
}
public void doSOSProfile(State state, int pc){
LegacyState legacystate = (LegacyState)state;
tracePC[tracePtr] = pc;
traceSP[tracePtr] = state.getSP();
traceR0[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R0);
traceR1[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R1);
traceR26[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R26);
traceR27[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R27);
traceR30[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R30);
traceR31[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R31);
tracePtr = (tracePtr + 1) % (tracelen);
return;
}
}
public void printMemoryMap(LegacyState l){
int rdByte;
int i;
TermUtil.printSeparator(Terminal.MAXLINE, "Memory Map");
for (i = 0; i < 256; i++){
int lrec, hrec;
if ((i % 16) == 0) Terminal.nextln();
rdByte = (int)l.getDataByte(memmap_addr + i);
rdByte &= 0xFF;
lrec = rdByte % 16;
hrec = rdByte / 16;
printMemoryMapByte(2*i, lrec);
printMemoryMapByte((2*i) + 1, hrec);
}
Terminal.nextln();
return;
}
public void printMemoryMapByte(int blknum, int mrec){
int domid;
domid = mrec % 8;
// Terminal.print(StringUtil.toDecimal((long)blknum, 3));
if (mrec > 8)
Terminal.print(")(");
else
Terminal.print("--");
Terminal.print(StringUtil.toBin((long)domid, 3));
return;
}
public void printExecTrace(Simulator s){
int i;
// Program p;
// AbstractInstr instr;
// p = s.getProgram();
TermUtil.printThinSeparator();
for (i = tracePtr - 2; i >= 0; i--){
// instr = p.readInstr(tracePC[i]);
Terminal.print("Addr: ");
Terminal.print(StringUtil.addrToString(tracePC[i]));
Terminal.print(" SP: ");
Terminal.print(StringUtil.addrToString(traceSP[i]));
Terminal.print(" R0: ");
Terminal.print(StringUtil.addrToString(traceR0[i]));
Terminal.print(" R1: ");
Terminal.print(StringUtil.addrToString(traceR1[i]));
Terminal.print(" R26: ");
Terminal.print(StringUtil.addrToString(traceR26[i]));
Terminal.print(" R27: ");
Terminal.print(StringUtil.addrToString(traceR27[i]));
Terminal.print(" R30: ");
Terminal.print(StringUtil.addrToString(traceR30[i]));
Terminal.print(" R31: ");
Terminal.println(StringUtil.addrToString(traceR31[i]));
}
for (i = (tracelen-1); i >= tracePtr; i--){
Terminal.print("Addr: ");
Terminal.print(StringUtil.addrToString(tracePC[i]));
Terminal.print(" SP: ");
Terminal.print(StringUtil.addrToString(traceSP[i]));
Terminal.print(" R0: ");
Terminal.print(StringUtil.addrToString(traceR0[i]));
Terminal.print(" R1: ");
Terminal.print(StringUtil.addrToString(traceR1[i]));
Terminal.print(" R26: ");
Terminal.print(StringUtil.addrToString(traceR26[i]));
Terminal.print(" R27: ");
Terminal.print(StringUtil.addrToString(traceR27[i]));
Terminal.print(" R30: ");
Terminal.print(StringUtil.addrToString(traceR30[i]));
Terminal.print(" R31: ");
Terminal.println(StringUtil.addrToString(traceR31[i]));
// instr = p.readInstr(tracePC[i]);
// TermUtil.reportQuantity(StringUtil.addrToString(tracePC[i]),
// instr.getName(),
// "SP:" + StringUtil.addrToString(traceSP[i]));
}
}
public void report(){
return;
}
}
public SOSCrashMonitor(){
super("The \"SOS Crash Monitor\" inserts a probe at SOS crash site " +
"and dumps detailed state report to screen.");
}
public avrora.monitors.Monitor newMonitor(Simulator s){
return new Mon(s);
}
} | tools/avrora/sos/monitor/SOSCrashMonitor.java | /**
* @file SOSCrashMonitor.java
* @brief Detailed crash report of SOS when it crashes
* @author Ram Kumar {[email protected]}
*/
package sos.monitor;
import avrora.monitors.Monitor;
import avrora.monitors.MonitorFactory;
import avrora.sim.Simulator;
import avrora.sim.State;
import avrora.core.Program;
import avrora.arch.AbstractInstr;
import avrora.arch.legacy.*;
import cck.util.Option;
import cck.util.Util;
import cck.text.TermUtil;
import cck.text.Terminal;
import cck.text.StringUtil;
import java.util.*;
public class SOSCrashMonitor extends MonitorFactory {
public final Option.Long CRASHADDR = options.newOption("crash-addr", 0, "Specify byte address of crash site.");
public final Option.Bool PROFBEFORE = options.newOption("profie-before-fire", false, "Profile before executing an instruction.");
public final Option.Long SFIEXCEPTIONADDR = options.newOption("sfi-exception-addr", 0, "Specify byte address of crash site.");
public final Option.Long TRACELEN = options.newOption("trace-len", 100, "Specify length of intr. trace");
public final Option.Long MEMMAPADDR = options.newOption("memmap-addr", 0, "Specify length of intr. trace");
public final Option.Long MALLOCADDR = options.newOption("malloc-addr", 0, "Specify length of intr. trace");
public final Option.Long FREEADDR = options.newOption("free-addr", 0, "Specify length of intr. trace");
public final Option.Long CHOWNADDR = options.newOption("chown-addr", 0, "Specify length of intr. trace");
public final Option.Long VMPOST = options.newOption("vm-post", 0, "Specify length of intr. trace");
public class Mon implements avrora.monitors.Monitor {
public final Simulator simulator;
public int tracelen;
public int tracePtr;
public int[] tracePC;
public int[] traceSP;
public int[] traceR0;
public int[] traceR1;
public int[] traceR26;
public int[] traceR27;
public int[] traceR30;
public int[] traceR31;
public int memmap_addr;
public int mallocaddr, freeaddr, chownaddr;
public boolean profilebefore;
Mon(Simulator s) {
simulator = s;
tracePtr = 0;
tracelen = (int)TRACELEN.get();
tracePC = new int[tracelen];
traceSP = new int[tracelen];
traceR0 = new int[tracelen];
traceR1 = new int[tracelen];
traceR26 = new int[tracelen];
traceR27 = new int[tracelen];
traceR30 = new int[tracelen];
traceR31 = new int[tracelen];
memmap_addr = (int)MEMMAPADDR.get();
int crashaddr = (int)CRASHADDR.get();
if (crashaddr != 0)
s.insertProbe(new SOSCrashProbe(), crashaddr);
int sfiexceptionaddr = (int)SFIEXCEPTIONADDR.get();
if (sfiexceptionaddr != 0)
s.insertProbe(new SOSSFIExceptionProbe(), sfiexceptionaddr);
mallocaddr = (int)MALLOCADDR.get();
if (mallocaddr != 0)
s.insertProbe(new SOSMemoryMapProbe(), mallocaddr);
freeaddr = (int)FREEADDR.get();
if (freeaddr != 0)
s.insertProbe(new SOSMemoryMapProbe(), freeaddr);
chownaddr = (int)CHOWNADDR.get();
if (chownaddr != 0)
s.insertProbe(new SOSMemoryMapProbe(), chownaddr);
int vmpost = (int)VMPOST.get();
if (vmpost != 0)
s.insertProbe(new SOSDVMProbe(), vmpost);
profilebefore = (boolean)PROFBEFORE.get();
s.insertProbe(new SOSTraceProbe());
}
public class SOSDVMProbe implements Simulator.Probe {
public void fireAfter(State state, int pc){
Simulator simul;
LegacyState legacystate = (LegacyState)state;
int did = legacystate.getRegisterUnsigned(LegacyRegister.R24);
int sid = legacystate.getRegisterUnsigned(LegacyRegister.R22);
int type = legacystate.getRegisterUnsigned(LegacyRegister.R20);
int len = legacystate.getRegisterUnsigned(LegacyRegister.R18);
TermUtil.printSeparator(Terminal.MAXLINE, "DVM POST");
TermUtil.reportQuantity("did: ", StringUtil.addrToString(did), " ");
TermUtil.reportQuantity("sid: ", StringUtil.addrToString(sid), " ");
TermUtil.reportQuantity("type: ", StringUtil.addrToString(type), " ");
TermUtil.reportQuantity("len: ", StringUtil.addrToString(len), " ");
simul = state.getSimulator();
simul.stop();
}
public void fireBefore(State state, int pc){
return;
}
}
public class SOSMemoryMapProbe implements Simulator.Probe {
public void fireAfter(State state, int pc){
LegacyState legacystate = (LegacyState)state;
if (pc == mallocaddr)
Terminal.println("Malloc");
if (pc == freeaddr)
Terminal.println("Free");
if (pc == chownaddr)
Terminal.println("Msg Take Data");
printMemoryMap(legacystate);
}
public void fireBefore(State state, int pc){
return;
}
}
public class SOSSFIExceptionProbe implements Simulator.Probe {
private final int SFI_HEAP_EXCEPTION = 3;
public void fireBefore(State state, int pc){
Simulator simul;
LegacyState legacystate = (LegacyState)state;
int regval = legacystate.getRegisterByte(LegacyRegister.R24);
simul = state.getSimulator();
TermUtil.printSeparator(Terminal.MAXLINE, "SFI Exception");
TermUtil.reportQuantity("Addr: ", StringUtil.addrToString(pc), " ");
TermUtil.reportQuantity("Cycles: ", state.getCycles(), " ");
TermUtil.reportQuantity("Stack: ", StringUtil.addrToString(state.getSP()), " ");
TermUtil.reportQuantity("Excpetion Code (R24): ", StringUtil.addrToString(regval), " ");
printExecTrace(simul);
if (regval == SFI_HEAP_EXCEPTION)
printMemoryMap(legacystate);
simul.stop();
}
public void fireAfter(State state, int pc){
return;
}
}
public class SOSCrashProbe implements Simulator.Probe {
public void fireBefore(State state, int pc){
TermUtil.printSeparator(Terminal.MAXLINE, "Crash Dump");
TermUtil.reportQuantity("Addr: ", StringUtil.addrToString(pc), " ");
TermUtil.reportQuantity("Cycles: ", state.getCycles(), " ");
TermUtil.reportQuantity("Stack: ", StringUtil.addrToString(state.getSP()), " ");
printExecTrace(state.getSimulator());
return;
}
public void fireAfter(State state, int pc){
return;
}
}
public class SOSTraceProbe implements Simulator.Probe{
public void fireBefore(State state, int pc){
if (profilebefore)
doSOSProfile(state, pc);
return;
}
public void fireAfter(State state, int pc){
if (!profilebefore)
doSOSProfile(state, pc);
return;
}
public void doSOSProfile(State state, int pc){
LegacyState legacystate = (LegacyState)state;
/*
if ((pc >= 46528) && (pc < 130048)){
Terminal.print("PC: ");
Terminal.print(StringUtil.addrToString(pc));
Terminal.nextln();
}
*/
tracePC[tracePtr] = pc;
traceSP[tracePtr] = state.getSP();
traceR0[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R0);
traceR1[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R1);
traceR26[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R26);
traceR27[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R27);
traceR30[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R30);
traceR31[tracePtr] = legacystate.getRegisterUnsigned(LegacyRegister.R31);
tracePtr = (tracePtr + 1) % (tracelen);
return;
}
}
public void printMemoryMap(LegacyState l){
int rdByte;
int i;
TermUtil.printSeparator(Terminal.MAXLINE, "Memory Map");
for (i = 0; i < 256; i++){
int lrec, hrec;
if ((i % 16) == 0) Terminal.nextln();
rdByte = (int)l.getDataByte(memmap_addr + i);
rdByte &= 0xFF;
lrec = rdByte % 16;
hrec = rdByte / 16;
printMemoryMapByte(2*i, lrec);
printMemoryMapByte((2*i) + 1, hrec);
}
Terminal.nextln();
return;
}
public void printMemoryMapByte(int blknum, int mrec){
int domid;
domid = mrec % 8;
// Terminal.print(StringUtil.toDecimal((long)blknum, 3));
if (mrec > 8)
Terminal.print(")(");
else
Terminal.print("--");
Terminal.print(StringUtil.toBin((long)domid, 3));
return;
}
public void printExecTrace(Simulator s){
int i;
// Program p;
// AbstractInstr instr;
// p = s.getProgram();
TermUtil.printThinSeparator();
for (i = tracePtr - 2; i >= 0; i--){
// instr = p.readInstr(tracePC[i]);
Terminal.print("Addr: ");
Terminal.print(StringUtil.addrToString(tracePC[i]));
Terminal.print(" SP: ");
Terminal.print(StringUtil.addrToString(traceSP[i]));
Terminal.print(" R0: ");
Terminal.print(StringUtil.addrToString(traceR0[i]));
Terminal.print(" R1: ");
Terminal.print(StringUtil.addrToString(traceR1[i]));
Terminal.print(" R26: ");
Terminal.print(StringUtil.addrToString(traceR26[i]));
Terminal.print(" R27: ");
Terminal.print(StringUtil.addrToString(traceR27[i]));
Terminal.print(" R30: ");
Terminal.print(StringUtil.addrToString(traceR30[i]));
Terminal.print(" R31: ");
Terminal.println(StringUtil.addrToString(traceR31[i]));
}
for (i = (tracelen-1); i >= tracePtr; i--){
Terminal.print("Addr: ");
Terminal.print(StringUtil.addrToString(tracePC[i]));
Terminal.print(" SP: ");
Terminal.print(StringUtil.addrToString(traceSP[i]));
Terminal.print(" R0: ");
Terminal.print(StringUtil.addrToString(traceR0[i]));
Terminal.print(" R1: ");
Terminal.print(StringUtil.addrToString(traceR1[i]));
Terminal.print(" R26: ");
Terminal.print(StringUtil.addrToString(traceR26[i]));
Terminal.print(" R27: ");
Terminal.print(StringUtil.addrToString(traceR27[i]));
Terminal.print(" R30: ");
Terminal.print(StringUtil.addrToString(traceR30[i]));
Terminal.print(" R31: ");
Terminal.println(StringUtil.addrToString(traceR31[i]));
// instr = p.readInstr(tracePC[i]);
// TermUtil.reportQuantity(StringUtil.addrToString(tracePC[i]),
// instr.getName(),
// "SP:" + StringUtil.addrToString(traceSP[i]));
}
}
public void report(){
return;
}
}
public SOSCrashMonitor(){
super("The \"SOS Crash Monitor\" inserts a probe at SOS crash site " +
"and dumps detailed state report to screen.");
}
public avrora.monitors.Monitor newMonitor(Simulator s){
return new Mon(s);
}
} | Avrora: SOSCrashmonitor - Enable option to profile before or after instruction fires
| tools/avrora/sos/monitor/SOSCrashMonitor.java | Avrora: SOSCrashmonitor - Enable option to profile before or after instruction fires |
|
Java | mit | 72105fb3494e6f9d0f337f2a29697c2d0eb56ba5 | 0 | diirt/diirt,berryma4/diirt,ControlSystemStudio/diirt,berryma4/diirt,berryma4/diirt,diirt/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,berryma4/diirt,richardfearn/diirt,richardfearn/diirt,richardfearn/diirt,diirt/diirt,diirt/diirt | /*
* Copyright 2010-11 Brookhaven National Laboratory
* All rights reserved. Use is subject to license terms.
*/
package org.epics.pvmanager.test;
import org.epics.pvmanager.PVWriterListener;
import org.junit.Before;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.epics.pvmanager.DataSource;
import org.epics.pvmanager.PV;
import org.epics.pvmanager.PVManager;
import org.epics.pvmanager.PVReader;
import org.epics.pvmanager.PVReaderListener;
import org.epics.pvmanager.PVWriter;
import org.epics.pvmanager.ReadFailException;
import org.epics.pvmanager.TimeoutException;
import org.epics.pvmanager.WriteFailException;
import org.hamcrest.Matchers;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import static org.epics.pvmanager.ExpressionLanguage.*;
import static org.epics.pvmanager.util.TimeDuration.*;
/**
*
* @author carcassi
*/
public class TestDataSourceTest {
public TestDataSourceTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
dataSource = new TestDataSource();
}
@AfterClass
public static void tearDownClass() throws Exception {
dataSource = null;
}
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
private static DataSource dataSource;
@Mock PVWriterListener writeListener;
@Mock PVReaderListener readListener;
@Test
public void channelDoesNotExist1() throws Exception {
PVReader<Object> pvReader = PVManager.read(channel("nothing")).from(dataSource).every(ms(10));
pvReader.addPVReaderListener(readListener);
Thread.sleep(15);
ReadFailException ex = (ReadFailException) pvReader.lastException();
assertThat(ex, not(nullValue()));
verify(readListener).pvChanged();
pvReader.close();
}
@Test
public void channelDoesNotExist2() throws Exception {
PVWriter<Object> pvWriter = PVManager.write(channel("nothing")).from(dataSource).async();
pvWriter.addPVWriterListener(writeListener);
Thread.sleep(15);
WriteFailException ex = (WriteFailException) pvWriter.lastWriteException();
assertThat(ex, not(nullValue()));
verify(writeListener).pvWritten();
pvWriter.close();
}
@Test
public void delayedWrite() throws Exception {
PVWriter<Object> pvWriter = PVManager.write(channel("delayedWrite")).from(dataSource).async();
pvWriter.addPVWriterListener(writeListener);
pvWriter.write("test");
Thread.sleep(15);
WriteFailException ex = (WriteFailException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, never()).pvWritten();
Thread.sleep(1000);
ex = (WriteFailException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener).pvWritten();
pvWriter.close();
Thread.sleep(30);
assertThat(dataSource.getChannels().get("delayedWrite").isConnected(), is(false));
}
@Test
public void delayedWriteWithTimeout() throws Exception {
PVWriter<Object> pvWriter = PVManager.write(channel("delayedWrite")).timeout(ms(500)).from(dataSource).async();
pvWriter.addPVWriterListener(writeListener);
pvWriter.write("test");
Thread.sleep(15);
TimeoutException ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, never()).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, not(nullValue()));
verify(writeListener).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, times(2)).pvWritten();
pvWriter.close();
Thread.sleep(30);
assertThat(dataSource.getChannels().get("delayedWrite").isConnected(), is(false));
}
@Test
public void delayedWriteWithTimeout2() throws Exception {
PVWriter<Object> pvWriter = PVManager.write(channel("delayedWrite")).timeout(ms(500)).from(dataSource).async();
pvWriter.addPVWriterListener(writeListener);
pvWriter.write("test");
Thread.sleep(15);
TimeoutException ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, never()).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, not(nullValue()));
verify(writeListener).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, times(2)).pvWritten();
// Write again
pvWriter.write("test2");
Thread.sleep(15);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, times(2)).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, not(nullValue()));
verify(writeListener, times(3)).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, times(4)).pvWritten();
pvWriter.close();
Thread.sleep(30);
assertThat(dataSource.getChannels().get("delayedWrite").isConnected(), is(false));
}
@Test
public void delayedReadConnectionWithTimeout() throws Exception {
PVReader<Object> pvReader = PVManager.read(channel("delayedConnection")).timeout(ms(500)).from(dataSource).every(ms(50));
pvReader.addPVReaderListener(readListener);
Thread.sleep(15);
TimeoutException ex = (TimeoutException) pvReader.lastException();
assertThat(ex, nullValue());
verify(readListener, never()).pvChanged();
Thread.sleep(500);
ex = (TimeoutException) pvReader.lastException();
assertThat(ex, not(nullValue()));
verify(readListener).pvChanged();
Thread.sleep(600);
ex = (TimeoutException) pvReader.lastException();
assertThat(ex, nullValue());
verify(readListener, times(2)).pvChanged();
assertThat((String) pvReader.getValue(), equalTo("Initial value"));
pvReader.close();
Thread.sleep(30);
assertThat(dataSource.getChannels().get("delayedConnection").isConnected(), is(false));
}
@Test
public void delayedReadOnPVWithTimeout() throws Exception {
PV<Object, Object> pv = PVManager.readAndWrite(channel("delayedConnection")).timeout(ms(500)).from(dataSource).asynchWriteAndReadEvery(ms(50));
pv.addPVReaderListener(readListener);
Thread.sleep(50);
TimeoutException ex = (TimeoutException) pv.lastException();
assertThat(ex, nullValue());
verify(readListener, never()).pvChanged();
Thread.sleep(500);
ex = (TimeoutException) pv.lastException();
assertThat(ex, not(nullValue()));
verify(readListener).pvChanged();
Thread.sleep(600);
ex = (TimeoutException) pv.lastException();
assertThat(ex, nullValue());
verify(readListener, times(2)).pvChanged();
assertThat((String) pv.getValue(), equalTo("Initial value"));
pv.close();
Thread.sleep(30);
assertThat(dataSource.getChannels().get("delayedConnection").isConnected(), is(false));
}
@Test
public void delayedReadOnPVWithTimeoutAndCustomMessage() throws Exception {
String message = "Ouch! Timeout!";
PV<Object, Object> pv = PVManager.readAndWrite(channel("delayedConnection")).timeout(ms(500), message).from(dataSource).asynchWriteAndReadEvery(ms(50));
pv.addPVReaderListener(readListener);
Thread.sleep(50);
TimeoutException ex = (TimeoutException) pv.lastException();
assertThat(ex, nullValue());
verify(readListener, never()).pvChanged();
Thread.sleep(500);
ex = (TimeoutException) pv.lastException();
assertThat(ex, not(nullValue()));
assertThat(ex.getMessage(), equalTo(message));
verify(readListener).pvChanged();
Thread.sleep(600);
ex = (TimeoutException) pv.lastException();
assertThat(ex, nullValue());
verify(readListener, times(2)).pvChanged();
assertThat((String) pv.getValue(), equalTo("Initial value"));
pv.close();
Thread.sleep(30);
assertThat(dataSource.getChannels().get("delayedConnection").isConnected(), is(false));
}
}
| PVManager/src/test/java/org/epics/pvmanager/test/TestDataSourceTest.java | /*
* Copyright 2010-11 Brookhaven National Laboratory
* All rights reserved. Use is subject to license terms.
*/
package org.epics.pvmanager.test;
import org.epics.pvmanager.PVWriterListener;
import org.junit.Before;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.epics.pvmanager.DataSource;
import org.epics.pvmanager.PV;
import org.epics.pvmanager.PVManager;
import org.epics.pvmanager.PVReader;
import org.epics.pvmanager.PVReaderListener;
import org.epics.pvmanager.PVWriter;
import org.epics.pvmanager.ReadFailException;
import org.epics.pvmanager.TimeoutException;
import org.epics.pvmanager.WriteFailException;
import org.hamcrest.Matchers;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import static org.epics.pvmanager.ExpressionLanguage.*;
import static org.epics.pvmanager.util.TimeDuration.*;
/**
*
* @author carcassi
*/
public class TestDataSourceTest {
public TestDataSourceTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
dataSource = new TestDataSource();
}
@AfterClass
public static void tearDownClass() throws Exception {
dataSource = null;
}
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
private static DataSource dataSource;
@Mock PVWriterListener writeListener;
@Mock PVReaderListener readListener;
@Test
public void channelDoesNotExist1() throws Exception {
PVReader<Object> pvReader = PVManager.read(channel("nothing")).from(dataSource).every(ms(10));
pvReader.addPVReaderListener(readListener);
Thread.sleep(15);
ReadFailException ex = (ReadFailException) pvReader.lastException();
assertThat(ex, not(nullValue()));
verify(readListener).pvChanged();
pvReader.close();
}
@Test
public void channelDoesNotExist2() throws Exception {
PVWriter<Object> pvWriter = PVManager.write(channel("nothing")).from(dataSource).async();
pvWriter.addPVWriterListener(writeListener);
Thread.sleep(15);
WriteFailException ex = (WriteFailException) pvWriter.lastWriteException();
assertThat(ex, not(nullValue()));
verify(writeListener).pvWritten();
pvWriter.close();
}
@Test
public void delayedWrite() throws Exception {
PVWriter<Object> pvWriter = PVManager.write(channel("delayedWrite")).from(dataSource).async();
pvWriter.addPVWriterListener(writeListener);
pvWriter.write("test");
Thread.sleep(15);
WriteFailException ex = (WriteFailException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, never()).pvWritten();
Thread.sleep(1000);
ex = (WriteFailException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener).pvWritten();
pvWriter.close();
Thread.sleep(15);
assertThat(dataSource.getChannels().get("delayedWrite").isConnected(), is(false));
}
@Test
public void delayedWriteWithTimeout() throws Exception {
PVWriter<Object> pvWriter = PVManager.write(channel("delayedWrite")).timeout(ms(500)).from(dataSource).async();
pvWriter.addPVWriterListener(writeListener);
pvWriter.write("test");
Thread.sleep(15);
TimeoutException ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, never()).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, not(nullValue()));
verify(writeListener).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, times(2)).pvWritten();
pvWriter.close();
Thread.sleep(15);
assertThat(dataSource.getChannels().get("delayedWrite").isConnected(), is(false));
}
@Test
public void delayedWriteWithTimeout2() throws Exception {
PVWriter<Object> pvWriter = PVManager.write(channel("delayedWrite")).timeout(ms(500)).from(dataSource).async();
pvWriter.addPVWriterListener(writeListener);
pvWriter.write("test");
Thread.sleep(15);
TimeoutException ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, never()).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, not(nullValue()));
verify(writeListener).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, times(2)).pvWritten();
// Write again
pvWriter.write("test2");
Thread.sleep(15);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, times(2)).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, not(nullValue()));
verify(writeListener, times(3)).pvWritten();
Thread.sleep(500);
ex = (TimeoutException) pvWriter.lastWriteException();
assertThat(ex, nullValue());
verify(writeListener, times(4)).pvWritten();
pvWriter.close();
Thread.sleep(15);
assertThat(dataSource.getChannels().get("delayedWrite").isConnected(), is(false));
}
@Test
public void delayedReadConnectionWithTimeout() throws Exception {
PVReader<Object> pvReader = PVManager.read(channel("delayedConnection")).timeout(ms(500)).from(dataSource).every(ms(50));
pvReader.addPVReaderListener(readListener);
Thread.sleep(15);
TimeoutException ex = (TimeoutException) pvReader.lastException();
assertThat(ex, nullValue());
verify(readListener, never()).pvChanged();
Thread.sleep(500);
ex = (TimeoutException) pvReader.lastException();
assertThat(ex, not(nullValue()));
verify(readListener).pvChanged();
Thread.sleep(600);
ex = (TimeoutException) pvReader.lastException();
assertThat(ex, nullValue());
verify(readListener, times(2)).pvChanged();
assertThat((String) pvReader.getValue(), equalTo("Initial value"));
pvReader.close();
Thread.sleep(15);
assertThat(dataSource.getChannels().get("delayedConnection").isConnected(), is(false));
}
@Test
public void delayedReadOnPVWithTimeout() throws Exception {
PV<Object, Object> pv = PVManager.readAndWrite(channel("delayedConnection")).timeout(ms(500)).from(dataSource).asynchWriteAndReadEvery(ms(50));
pv.addPVReaderListener(readListener);
Thread.sleep(50);
TimeoutException ex = (TimeoutException) pv.lastException();
assertThat(ex, nullValue());
verify(readListener, never()).pvChanged();
Thread.sleep(500);
ex = (TimeoutException) pv.lastException();
assertThat(ex, not(nullValue()));
verify(readListener).pvChanged();
Thread.sleep(600);
ex = (TimeoutException) pv.lastException();
assertThat(ex, nullValue());
verify(readListener, times(2)).pvChanged();
assertThat((String) pv.getValue(), equalTo("Initial value"));
pv.close();
Thread.sleep(15);
assertThat(dataSource.getChannels().get("delayedConnection").isConnected(), is(false));
}
@Test
public void delayedReadOnPVWithTimeoutAndCustomMessage() throws Exception {
String message = "Ouch! Timeout!";
PV<Object, Object> pv = PVManager.readAndWrite(channel("delayedConnection")).timeout(ms(500), message).from(dataSource).asynchWriteAndReadEvery(ms(50));
pv.addPVReaderListener(readListener);
Thread.sleep(50);
TimeoutException ex = (TimeoutException) pv.lastException();
assertThat(ex, nullValue());
verify(readListener, never()).pvChanged();
Thread.sleep(500);
ex = (TimeoutException) pv.lastException();
assertThat(ex, not(nullValue()));
assertThat(ex.getMessage(), equalTo(message));
verify(readListener).pvChanged();
Thread.sleep(600);
ex = (TimeoutException) pv.lastException();
assertThat(ex, nullValue());
verify(readListener, times(2)).pvChanged();
assertThat((String) pv.getValue(), equalTo("Initial value"));
pv.close();
Thread.sleep(15);
assertThat(dataSource.getChannels().get("delayedConnection").isConnected(), is(false));
}
}
| Increase delay before checking that connections were closed in the datasource.
| PVManager/src/test/java/org/epics/pvmanager/test/TestDataSourceTest.java | Increase delay before checking that connections were closed in the datasource. |
|
Java | mit | 07d990a966bac99ac23c62a64be5d5c10b1b2880 | 0 | MondayHopscotch/Jump,bitDecayGames/Jump | package com.bitdecay.jump.collision;
import java.util.*;
import com.bitdecay.jump.BitBody;
import com.bitdecay.jump.BodyType;
import com.bitdecay.jump.geom.*;
import com.bitdecay.jump.level.Level;
import com.bitdecay.jump.level.builder.TileObject;
/**
* A Pseudo-Physics simulation world. Will step according to all body's
* properties, but properties are publicly accessible to allow for total
* control.
*
* @author Monday
*
*/
public class BitWorld {
public static final String VERSION = "0.1.2";
public static final float STEP_SIZE = 1 / 120f;
/**
* Holds left-over time when there isn't enough time for a full
* {@link #STEP_SIZE}
*/
private float extraStepTime = 0;
private float timePassed;
private int tileSize = 0;
private BitPointInt gridOffset = new BitPointInt(0, 0);
private BitBody[][] gridObjects = new BitBody[0][0];
private List<BitBody> dynamicBodies = new ArrayList<>();
private List<BitBody> kineticBodies = new ArrayList<>();
private List<BitBody> staticBodies = new ArrayList<>();
/**
* A map of x to y to an occupying body.
*/
private Map<Integer, Map<Integer, Set<BitBody>>> occupiedSpaces;
private Map<BitBody, BitResolution> pendingResolutions;
private Map<BitBody, Set<BitBody>> contacts;
public static BitPoint gravity = new BitPoint(0, 0);
public static BitPoint maxSpeed = new BitPoint(2000, 2000);
private List<BitBody> pendingAdds;
private List<BitBody> pendingRemoves;
public final List<BitRectangle> resolvedCollisions = new ArrayList<>();
public final List<BitRectangle> unresolvedCollisions = new ArrayList<>();
public BitWorld() {
pendingAdds = new ArrayList<>();
pendingRemoves = new ArrayList<>();
occupiedSpaces = new HashMap<>();
pendingResolutions = new HashMap<>();
contacts = new HashMap<>();
}
public BitPoint getGravity() {
return gravity;
}
public void setGravity(float x, float y) {
this.gravity.x = x;
this.gravity.y = y;
}
public void addBody(BitBody body) {
pendingAdds.add(body);
}
public void removeBody(BitBody body) {
pendingRemoves.add(body);
}
/**
* steps the physics world in {@link BitWorld#STEP_SIZE} time steps. Any
* left over will be rolled over in to the next call to this method.
*
* @param delta
* @return true if the world stepped, false otherwise
*/
public boolean step(float delta) {
if (gridObjects == null) {
System.err.println("No level has been set into the world. Exiting...");
System.exit(-1);
} else if (tileSize <= 0) {
System.err.println("Tile size has not been set. Exiting");
System.exit(-1);
}
if (delta <= 0) {
nonStep();
return false;
}
boolean stepped = false;
//add any left over time from last call to step();
delta += extraStepTime;
while (delta > STEP_SIZE) {
stepped = true;
resolvedCollisions.clear();
unresolvedCollisions.clear();
internalStep(STEP_SIZE);
delta -= STEP_SIZE;
}
// store off our leftover so it can be added in next time
extraStepTime = delta;
return stepped;
}
public void nonStep() {
doAddRemoves();
}
private void internalStep(final float delta) {
timePassed += delta;
// make sure world contains everything it should
doAddRemoves();
occupiedSpaces.clear();
/**
* FIRST, MOVE EVERYTHING
*/
dynamicBodies.stream().forEach(body -> {
if (body.active) {
body.previousAttempt.set(body.currentAttempt);
body.lastPosition.set(body.aabb.xy);
updateDynamics(body, delta);
updateControl(body, delta);
moveBody(body, delta);
updateOccupiedSpaces(body);
resetCollisions(body);
}
});
kineticBodies.stream().forEach(body -> {
if (body.active) {
body.previousAttempt.set(body.currentAttempt);
body.lastPosition.set(body.aabb.xy);
updateControl(body, delta);
moveBody(body, delta);
updateKinetics(body);
updateOccupiedSpaces(body);
resetCollisions(body);
}
});
staticBodies.stream().forEach(body -> {
if (body.active) {
updateOccupiedSpaces(body);
}
});
/**
* END OF MOVING EVERYTHING
*/
/**
* BUILD COLLISIONS
*/
dynamicBodies.stream().forEach(body -> {
if (body.active) {
buildLevelCollisions(body);
expireContact(body);
findNewContact(body);
}
});
/**
* END COLLISIONS
*/
resolveAndApplyPendingResolutions();
dynamicBodies.parallelStream().forEach(body -> {
if (body.active && body.stateWatcher != null) {
body.stateWatcher.update(body);
}
});
}
public void updateControl(BitBody body, float delta) {
if (body.controller != null) {
body.controller.update(delta, body);
}
}
public void updateDynamics(BitBody body, float delta) {
if (body.gravitational) {
body.velocity.add(gravity.scale(delta));
}
}
public void updateKinetics(BitBody body) {
for (BitBody child : body.children) {
/*
* we make sure to move the child just slightly less
* than the parent to guarantee that it still
* collides if nothing else influences it's motion
*/
BitPoint influence = body.currentAttempt.shrink(MathUtils.FLOAT_PRECISION);
child.aabb.translate(influence);
// the child did attempt to move this additional amount according to our engine
child.currentAttempt.add(influence);
}
body.children.clear();
}
public void moveBody(BitBody body, float delta) {
body.velocity.x = Math.min(Math.abs(body.velocity.x), maxSpeed.x) * (body.velocity.x < 0 ? -1 : 1);
body.velocity.y = Math.min(Math.abs(body.velocity.y), maxSpeed.y) * (body.velocity.y < 0 ? -1 : 1);
body.currentAttempt = body.velocity.scale(delta);
body.aabb.translate(body.currentAttempt);
}
public void resetCollisions(BitBody body) {
// all dynamicBodies are assumed to be not grounded unless a collision happens this step.
body.grounded = false;
// all dynamicBodies assumed to be independent unless a lineage collision happens this step.
body.parent = null;
}
private void doAddRemoves() {
dynamicBodies.removeAll(pendingRemoves);
kineticBodies.removeAll(pendingRemoves);
staticBodies.removeAll(pendingRemoves);
pendingRemoves.stream().forEach(body -> contacts.remove(body));
pendingRemoves.clear();
for (BitBody body : pendingAdds) {
if (BodyType.DYNAMIC == body.bodyType) {
dynamicBodies.add(body);
}
if (BodyType.KINETIC == body.bodyType) {
kineticBodies.add(body);
}
if (BodyType.STATIC == body.bodyType) {
staticBodies.add(body);
}
contacts.put(body, new HashSet<>());
}
pendingAdds.clear();
}
private void resolveAndApplyPendingResolutions() {
dynamicBodies.forEach(body -> {
if (pendingResolutions.containsKey(body)) {
pendingResolutions.get(body).resolve(this);
applyResolution(body, pendingResolutions.get(body));
} else {
body.lastResolution.set(0,0);
}
});
pendingResolutions.clear();
}
private void expireContact(BitBody body) {
Iterator<BitBody> iterator = contacts.get(body).iterator();
BitBody otherBody = null;
while(iterator.hasNext()) {
otherBody = iterator.next();
if (GeomUtils.intersection(body.aabb, otherBody.aabb) == null) {
iterator.remove();
for (ContactListener listener : body.getContactListeners()) {
listener.contactEnded(otherBody);
}
for (ContactListener listener : otherBody.getContactListeners()) {
listener.contactEnded(body);
}
}
}
}
private void findNewContact(BitBody body) {
// We need to update each body against the level grid so we only collide things worth colliding
BitPoint startCell = body.aabb.xy.floorDivideBy(tileSize, tileSize).minus(gridOffset);
int endX = (int) (startCell.x + Math.ceil(1.0 * body.aabb.width / tileSize));
int endY = (int) (startCell.y + Math.ceil(1.0 * body.aabb.height / tileSize));
for (int x = (int) startCell.x; x <= endX; x++) {
if (!occupiedSpaces.containsKey(x)) {
continue;
}
for (int y = (int) startCell.y; y <= endY; y++) {
if (!occupiedSpaces.get(x).containsKey(y)) {
continue;
}
for (BitBody otherBody : occupiedSpaces.get(x).get(y)) {
if (otherBody.bodyType == BodyType.KINETIC) {
// kinetic platforms currently also flag contacts with dynamic bodies
checkForNewCollision(body, otherBody);
}
checkContact(body, otherBody);
}
}
}
}
private void checkContact(BitBody body, BitBody otherBody) {
BitRectangle intersection = GeomUtils.intersection(body.aabb, otherBody.aabb);
if (intersection != null) {
if (!contacts.get(body).contains(otherBody)) {
contacts.get(body).add(otherBody);
for (ContactListener listener : body.getContactListeners()) {
listener.contactStarted(otherBody);
}
for (ContactListener listener : otherBody.getContactListeners()) {
listener.contactStarted(body);
}
}
}
}
private void buildLevelCollisions(BitBody body) {
// 1. determine tile that x,y lives in
BitPoint startCell = body.aabb.xy.floorDivideBy(tileSize, tileSize).minus(gridOffset);
// 2. determine width/height in tiles
int endX = (int) (startCell.x + Math.ceil(1.0 * body.aabb.width / tileSize));
int endY = (int) (startCell.y + Math.ceil(1.0 * body.aabb.height / tileSize));
// 3. loop over those all occupied tiles
for (int x = (int) startCell.x; x <= endX; x++) {
for (int y = (int) startCell.y; y <= endY; y++) {
// ensure valid cell
if (ArrayUtilities.onGrid(gridObjects, x, y) && gridObjects[x][y] != null) {
BitBody checkObj = gridObjects[x][y];
checkForNewCollision(body, checkObj);
}
}
}
}
private void updateOccupiedSpaces(BitBody body) {
// 1. determine tile that x,y lives in
BitPoint startCell = body.aabb.xy.floorDivideBy(tileSize, tileSize).minus(gridOffset);
// 2. determine width/height in tiles
int endX = (int) (startCell.x + Math.ceil(1.0 * body.aabb.width / tileSize));
int endY = (int) (startCell.y + Math.ceil(1.0 * body.aabb.height / tileSize));
// 3. loop over those all occupied tiles
for (int x = (int) startCell.x; x <= endX; x++) {
if (!occupiedSpaces.containsKey(x)) {
occupiedSpaces.put(x, new HashMap<Integer, Set<BitBody>>());
}
for (int y = (int) startCell.y; y <= endY; y++) {
if (!occupiedSpaces.get(x).containsKey(y)) {
occupiedSpaces.get(x).put(y, new HashSet<BitBody>());
}
// mark the body as occupying the current grid coordinate
occupiedSpaces.get(x).get(y).add(body);
}
}
}
private void applyResolution(BitBody body, BitResolution resolution) {
if (resolution.resolution.x != 0 || resolution.resolution.y != 0) {
body.aabb.translate(resolution.resolution);
if (resolution.haltX) {
body.velocity.x = 0;
}
if (resolution.haltY) {
body.velocity.y = 0;
}
}
body.lastResolution = resolution.resolution;
}
/**
* A simple method that sees if there is a collision and adds it to the
* {@link BitResolution} as something that needs to be handled at the time
* of resolution.
*
* @param body will always be a dynamic body with current code
* @param against
*/
private void checkForNewCollision(BitBody body, BitBody against) {
BitRectangle insec = GeomUtils.intersection(body.aabb, against.aabb);
if (insec != null) {
if (!pendingResolutions.containsKey(body)) {
pendingResolutions.put(body, new SATStrategy(body));
}
BitResolution resolution = pendingResolutions.get(body);
//TODO: This can definitely be made more efficient via a hash map or something of the like
for (BitCollision collision : resolution.collisions) {
if (collision.otherBody == against) {
return;
}
}
resolution.collisions.add(new BitCollision(insec, against));
}
}
public List<BitBody> getDynamicBodies() {
return Collections.unmodifiableList(dynamicBodies);
}
public List<BitBody> getKineticBodies() {
return Collections.unmodifiableList(kineticBodies);
}
public List<BitBody> getStaticBodies() {
return Collections.unmodifiableList(staticBodies);
}
public void setTileSize(int tileSize) {
this.tileSize = tileSize;
}
public void setGridOffset(BitPointInt bodyOffset) {
this.gridOffset = bodyOffset;
}
public void setLevel(Level level) {
if (tileSize <= 0) {
System.err.println("Tile Size cannot be less than 1");
System.exit(-2);
}
tileSize = level.tileSize;
gridOffset = level.gridOffset;
parseGrid(level.gridObjects);
}
public void setGrid(TileObject[][] grid) {
parseGrid(grid);
}
private void parseGrid(TileObject[][] grid) {
gridObjects = new BitBody[grid.length][grid[0].length];
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid[0].length; y++) {
if (grid[x][y] != null) {
gridObjects[x][y] = grid[x][y].buildBody();
}
}
}
}
public BitBody[][] getGrid() {
return gridObjects;
}
public int getTileSize() {
return tileSize;
}
public BitPointInt getBodyOffset() {
return gridOffset;
}
public void setObjects(Collection<BitBody> otherObjects) {
removeAllBodies();
pendingAdds.addAll(otherObjects);
}
public void removeAllBodies() {
pendingRemoves.addAll(dynamicBodies);
pendingRemoves.addAll(kineticBodies);
pendingRemoves.addAll(staticBodies);
pendingAdds.clear();
}
public float getTimePassed() {
return timePassed;
}
public void resetTimePassed() {
timePassed = 0;
}
}
| jump-core/src/main/java/com/bitdecay/jump/collision/BitWorld.java | package com.bitdecay.jump.collision;
import java.util.*;
import com.bitdecay.jump.BitBody;
import com.bitdecay.jump.BodyType;
import com.bitdecay.jump.geom.*;
import com.bitdecay.jump.level.Level;
import com.bitdecay.jump.level.builder.TileObject;
/**
* A Pseudo-Physics simulation world. Will step according to all body's
* properties, but properties are publicly accessible to allow for total
* control.
*
* @author Monday
*
*/
public class BitWorld {
public static final String VERSION = "0.1.2";
public static final float STEP_SIZE = 1 / 120f;
/**
* Holds left-over time when there isn't enough time for a full
* {@link #STEP_SIZE}
*/
private float extraStepTime = 0;
private float timePassed;
private int tileSize = 0;
private BitPointInt gridOffset = new BitPointInt(0, 0);
private BitBody[][] gridObjects = new BitBody[0][0];
private List<BitBody> dynamicBodies = new ArrayList<>();
private List<BitBody> kineticBodies = new ArrayList<>();
private List<BitBody> staticBodies = new ArrayList<>();
/**
* A map of x to y to an occupying body.
*/
private Map<Integer, Map<Integer, Set<BitBody>>> occupiedSpaces;
private Map<BitBody, BitResolution> pendingResolutions;
private Map<BitBody, Set<BitBody>> contacts;
public static BitPoint gravity = new BitPoint(0, 0);
public static BitPoint maxSpeed = new BitPoint(2000, 2000);
private List<BitBody> pendingAdds;
private List<BitBody> pendingRemoves;
public final List<BitRectangle> resolvedCollisions = new ArrayList<>();
public final List<BitRectangle> unresolvedCollisions = new ArrayList<>();
public BitWorld() {
pendingAdds = new ArrayList<>();
pendingRemoves = new ArrayList<>();
occupiedSpaces = new HashMap<>();
pendingResolutions = new HashMap<>();
contacts = new HashMap<>();
}
public BitPoint getGravity() {
return gravity;
}
public void setGravity(float x, float y) {
this.gravity.x = x;
this.gravity.y = y;
}
public void addBody(BitBody body) {
pendingAdds.add(body);
}
public void removeBody(BitBody body) {
pendingRemoves.add(body);
}
/**
* steps the physics world in {@link BitWorld#STEP_SIZE} time steps. Any
* left over will be rolled over in to the next call to this method.
*
* @param delta
* @return true if the world stepped, false otherwise
*/
public boolean step(float delta) {
if (gridObjects == null) {
System.err.println("No level has been set into the world. Exiting...");
System.exit(-1);
} else if (tileSize <= 0) {
System.err.println("Tile size has not been set. Exiting");
System.exit(-1);
}
// delta *= .05f;
boolean stepped = false;
//add any left over time from last call to step();
delta += extraStepTime;
while (delta > STEP_SIZE) {
stepped = true;
resolvedCollisions.clear();
unresolvedCollisions.clear();
internalStep(STEP_SIZE);
delta -= STEP_SIZE;
}
// store off our leftover so it can be added in next time
extraStepTime = delta;
return stepped;
}
public void nonStep() {
doAddRemoves();
}
private void internalStep(final float delta) {
if (delta <= 0) {
nonStep();
return;
}
timePassed += delta;
// make sure world contains everything it should
doAddRemoves();
occupiedSpaces.clear();
/**
* FIRST, MOVE EVERYTHING
*/
dynamicBodies.stream().forEach(body -> {
if (body.active) {
body.previousAttempt.set(body.currentAttempt);
body.lastPosition.set(body.aabb.xy);
updateDynamics(body, delta);
updateControl(body, delta);
moveBody(body, delta);
updateOccupiedSpaces(body);
resetCollisions(body);
}
});
kineticBodies.stream().forEach(body -> {
if (body.active) {
body.previousAttempt.set(body.currentAttempt);
body.lastPosition.set(body.aabb.xy);
updateControl(body, delta);
moveBody(body, delta);
updateKinetics(body);
updateOccupiedSpaces(body);
resetCollisions(body);
}
});
staticBodies.stream().forEach(body -> {
if (body.active) {
updateOccupiedSpaces(body);
}
});
/**
* END OF MOVING EVERYTHING
*/
/**
* BUILD COLLISIONS
*/
dynamicBodies.stream().forEach(body -> {
if (body.active) {
buildLevelCollisions(body);
expireContact(body);
findNewContact(body);
}
});
/**
* END COLLISIONS
*/
resolveAndApplyPendingResolutions();
dynamicBodies.parallelStream().forEach(body -> {
if (body.active && body.stateWatcher != null) {
body.stateWatcher.update(body);
}
});
}
public void updateControl(BitBody body, float delta) {
if (body.controller != null) {
body.controller.update(delta, body);
}
}
public void updateDynamics(BitBody body, float delta) {
if (body.gravitational) {
body.velocity.add(gravity.scale(delta));
}
}
public void updateKinetics(BitBody body) {
for (BitBody child : body.children) {
/*
* we make sure to move the child just slightly less
* than the parent to guarantee that it still
* collides if nothing else influences it's motion
*/
BitPoint influence = body.currentAttempt.shrink(MathUtils.FLOAT_PRECISION);
child.aabb.translate(influence);
// the child did attempt to move this additional amount according to our engine
child.currentAttempt.add(influence);
}
body.children.clear();
}
public void moveBody(BitBody body, float delta) {
body.velocity.x = Math.min(Math.abs(body.velocity.x), maxSpeed.x) * (body.velocity.x < 0 ? -1 : 1);
body.velocity.y = Math.min(Math.abs(body.velocity.y), maxSpeed.y) * (body.velocity.y < 0 ? -1 : 1);
body.currentAttempt = body.velocity.scale(delta);
body.aabb.translate(body.currentAttempt);
}
public void resetCollisions(BitBody body) {
// all dynamicBodies are assumed to be not grounded unless a collision happens this step.
body.grounded = false;
// all dynamicBodies assumed to be independent unless a lineage collision happens this step.
body.parent = null;
}
private void doAddRemoves() {
dynamicBodies.removeAll(pendingRemoves);
kineticBodies.removeAll(pendingRemoves);
staticBodies.removeAll(pendingRemoves);
pendingRemoves.stream().forEach(body -> contacts.remove(body));
pendingRemoves.clear();
for (BitBody body : pendingAdds) {
if (BodyType.DYNAMIC == body.bodyType) {
dynamicBodies.add(body);
}
if (BodyType.KINETIC == body.bodyType) {
kineticBodies.add(body);
}
if (BodyType.STATIC == body.bodyType) {
staticBodies.add(body);
}
contacts.put(body, new HashSet<>());
}
pendingAdds.clear();
}
private void resolveAndApplyPendingResolutions() {
dynamicBodies.forEach(body -> {
if (pendingResolutions.containsKey(body)) {
pendingResolutions.get(body).resolve(this);
applyResolution(body, pendingResolutions.get(body));
} else {
body.lastResolution.set(0,0);
}
});
pendingResolutions.clear();
}
private void expireContact(BitBody body) {
Iterator<BitBody> iterator = contacts.get(body).iterator();
BitBody otherBody = null;
while(iterator.hasNext()) {
otherBody = iterator.next();
if (GeomUtils.intersection(body.aabb, otherBody.aabb) == null) {
iterator.remove();
for (ContactListener listener : body.getContactListeners()) {
listener.contactEnded(otherBody);
}
for (ContactListener listener : otherBody.getContactListeners()) {
listener.contactEnded(body);
}
}
}
}
private void findNewContact(BitBody body) {
// We need to update each body against the level grid so we only collide things worth colliding
BitPoint startCell = body.aabb.xy.floorDivideBy(tileSize, tileSize).minus(gridOffset);
int endX = (int) (startCell.x + Math.ceil(1.0 * body.aabb.width / tileSize));
int endY = (int) (startCell.y + Math.ceil(1.0 * body.aabb.height / tileSize));
for (int x = (int) startCell.x; x <= endX; x++) {
if (!occupiedSpaces.containsKey(x)) {
continue;
}
for (int y = (int) startCell.y; y <= endY; y++) {
if (!occupiedSpaces.get(x).containsKey(y)) {
continue;
}
for (BitBody otherBody : occupiedSpaces.get(x).get(y)) {
if (otherBody.bodyType == BodyType.KINETIC) {
// kinetic platforms currently also flag contacts with dynamic bodies
checkForNewCollision(body, otherBody);
}
checkContact(body, otherBody);
}
}
}
}
private void checkContact(BitBody body, BitBody otherBody) {
BitRectangle intersection = GeomUtils.intersection(body.aabb, otherBody.aabb);
if (intersection != null) {
if (!contacts.get(body).contains(otherBody)) {
contacts.get(body).add(otherBody);
for (ContactListener listener : body.getContactListeners()) {
listener.contactStarted(otherBody);
}
for (ContactListener listener : otherBody.getContactListeners()) {
listener.contactStarted(body);
}
}
}
}
private void buildLevelCollisions(BitBody body) {
// 1. determine tile that x,y lives in
BitPoint startCell = body.aabb.xy.floorDivideBy(tileSize, tileSize).minus(gridOffset);
// 2. determine width/height in tiles
int endX = (int) (startCell.x + Math.ceil(1.0 * body.aabb.width / tileSize));
int endY = (int) (startCell.y + Math.ceil(1.0 * body.aabb.height / tileSize));
// 3. loop over those all occupied tiles
for (int x = (int) startCell.x; x <= endX; x++) {
for (int y = (int) startCell.y; y <= endY; y++) {
// ensure valid cell
if (ArrayUtilities.onGrid(gridObjects, x, y) && gridObjects[x][y] != null) {
BitBody checkObj = gridObjects[x][y];
checkForNewCollision(body, checkObj);
}
}
}
}
private void updateOccupiedSpaces(BitBody body) {
// 1. determine tile that x,y lives in
BitPoint startCell = body.aabb.xy.floorDivideBy(tileSize, tileSize).minus(gridOffset);
// 2. determine width/height in tiles
int endX = (int) (startCell.x + Math.ceil(1.0 * body.aabb.width / tileSize));
int endY = (int) (startCell.y + Math.ceil(1.0 * body.aabb.height / tileSize));
// 3. loop over those all occupied tiles
for (int x = (int) startCell.x; x <= endX; x++) {
if (!occupiedSpaces.containsKey(x)) {
occupiedSpaces.put(x, new HashMap<Integer, Set<BitBody>>());
}
for (int y = (int) startCell.y; y <= endY; y++) {
if (!occupiedSpaces.get(x).containsKey(y)) {
occupiedSpaces.get(x).put(y, new HashSet<BitBody>());
}
// mark the body as occupying the current grid coordinate
occupiedSpaces.get(x).get(y).add(body);
}
}
}
private void applyResolution(BitBody body, BitResolution resolution) {
if (resolution.resolution.x != 0 || resolution.resolution.y != 0) {
body.aabb.translate(resolution.resolution);
if (resolution.haltX) {
body.velocity.x = 0;
}
if (resolution.haltY) {
body.velocity.y = 0;
}
}
body.lastResolution = resolution.resolution;
}
/**
* A simple method that sees if there is a collision and adds it to the
* {@link BitResolution} as something that needs to be handled at the time
* of resolution.
*
* @param body will always be a dynamic body with current code
* @param against
*/
private void checkForNewCollision(BitBody body, BitBody against) {
BitRectangle insec = GeomUtils.intersection(body.aabb, against.aabb);
if (insec != null) {
if (!pendingResolutions.containsKey(body)) {
pendingResolutions.put(body, new SATStrategy(body));
}
BitResolution resolution = pendingResolutions.get(body);
//TODO: This can definitely be made more efficient via a hash map or something of the like
for (BitCollision collision : resolution.collisions) {
if (collision.otherBody == against) {
return;
}
}
resolution.collisions.add(new BitCollision(insec, against));
}
}
public List<BitBody> getDynamicBodies() {
return Collections.unmodifiableList(dynamicBodies);
}
public List<BitBody> getKineticBodies() {
return Collections.unmodifiableList(kineticBodies);
}
public List<BitBody> getStaticBodies() {
return Collections.unmodifiableList(staticBodies);
}
public void setTileSize(int tileSize) {
this.tileSize = tileSize;
}
public void setGridOffset(BitPointInt bodyOffset) {
this.gridOffset = bodyOffset;
}
public void setLevel(Level level) {
if (tileSize <= 0) {
System.err.println("Tile Size cannot be less than 1");
System.exit(-2);
}
tileSize = level.tileSize;
gridOffset = level.gridOffset;
parseGrid(level.gridObjects);
}
public void setGrid(TileObject[][] grid) {
parseGrid(grid);
}
private void parseGrid(TileObject[][] grid) {
gridObjects = new BitBody[grid.length][grid[0].length];
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid[0].length; y++) {
if (grid[x][y] != null) {
gridObjects[x][y] = grid[x][y].buildBody();
}
}
}
}
public BitBody[][] getGrid() {
return gridObjects;
}
public int getTileSize() {
return tileSize;
}
public BitPointInt getBodyOffset() {
return gridOffset;
}
public void setObjects(Collection<BitBody> otherObjects) {
removeAllBodies();
pendingAdds.addAll(otherObjects);
}
public void removeAllBodies() {
pendingRemoves.addAll(dynamicBodies);
pendingRemoves.addAll(kineticBodies);
pendingRemoves.addAll(staticBodies);
pendingAdds.clear();
}
public float getTimePassed() {
return timePassed;
}
public void resetTimePassed() {
timePassed = 0;
}
}
| Remove confusing step logic
| jump-core/src/main/java/com/bitdecay/jump/collision/BitWorld.java | Remove confusing step logic |
|
Java | mit | 7956f7fdc1a65c3084880bd5056b8a7ad515977f | 0 | Evisceration/ExecutionLibrary | package alexander.martinz.libs.execution;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeoutException;
import alexander.martinz.libs.execution.binaries.Installer;
import alexander.martinz.libs.execution.exceptions.RootDeniedException;
public class ShellManager {
private static final String TAG = ShellManager.class.getSimpleName();
private static ShellManager sInstance;
private static final ArrayList<RootShell> rootShells = new ArrayList<>();
private static final ArrayList<NormalShell> normalShells = new ArrayList<>();
private ShellManager() {
cleanupShells();
}
@NonNull public static ShellManager get() {
if (sInstance == null) {
sInstance = new ShellManager();
}
return sInstance;
}
public ShellManager installBusyBox(@NonNull Context context) {
Installer.installBusyBox(context);
return this;
}
@Nullable public RootShell getRootShell() {
return getRootShell(false);
}
@Nullable public RootShell getRootShell(boolean newShell) {
RootShell rootShell;
synchronized (rootShells) {
if (!newShell && rootShells.size() > 0) {
rootShell = rootShells.get(0);
if (rootShell != null) {
return rootShell;
}
}
}
rootShell = createRootShell();
synchronized (rootShells) {
rootShells.add(rootShell);
}
return rootShell;
}
@Nullable private RootShell createRootShell() {
try {
return new RootShell();
} catch (IOException | TimeoutException | RootDeniedException e) {
if (ShellLogger.DEBUG) {
Log.e(TAG, "Error creating new root shell", e);
}
}
return null;
}
@Nullable public NormalShell getNormalShell() {
return getNormalShell(false);
}
@Nullable public NormalShell getNormalShell(boolean newShell) {
NormalShell normalShell;
synchronized (normalShells) {
if (!newShell && normalShells.size() > 0) {
normalShell = normalShells.get(0);
if (normalShell != null) {
return normalShell;
}
}
}
normalShell = createNormalShell();
synchronized (normalShells) {
normalShells.add(normalShell);
}
return normalShell;
}
@Nullable private NormalShell createNormalShell() {
try {
return new NormalShell();
} catch (IOException | TimeoutException | RootDeniedException e) {
if (ShellLogger.DEBUG) {
Log.e(TAG, "Error creating new shell", e);
}
}
return null;
}
public void cleanupRootShells() {
synchronized (rootShells) {
if (rootShells.size() > 0) {
final Iterator<RootShell> rootShellIterator = rootShells.iterator();
while (rootShellIterator.hasNext()) {
final RootShell rootShell = rootShellIterator.next();
rootShell.close();
rootShellIterator.remove();
}
rootShells.clear();
}
}
}
public void cleanupNormalShells() {
synchronized (normalShells) {
if (normalShells.size() > 0) {
final Iterator<NormalShell> normalShellIterator = normalShells.iterator();
while (normalShellIterator.hasNext()) {
final NormalShell normalShell = normalShellIterator.next();
normalShell.close();
normalShellIterator.remove();
}
normalShells.clear();
}
}
}
public int getNormalShellCount() {
synchronized (normalShells) {
return normalShells.size();
}
}
public int getRootShellCount() {
synchronized (rootShells) {
return rootShells.size();
}
}
public void cleanupShells() {
cleanupRootShells();
cleanupNormalShells();
}
public void onDestroy() {
cleanupShells();
}
}
| library/src/main/java/alexander/martinz/libs/execution/ShellManager.java | package alexander.martinz.libs.execution;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeoutException;
import alexander.martinz.libs.execution.binaries.Installer;
import alexander.martinz.libs.execution.exceptions.RootDeniedException;
public class ShellManager {
private static final String TAG = ShellManager.class.getSimpleName();
private static ShellManager sInstance;
private static ArrayList<RootShell> rootShells = new ArrayList<>();
private static ArrayList<NormalShell> normalShells = new ArrayList<>();
private ShellManager() {
cleanupShells();
}
@Deprecated @NonNull public static ShellManager get(@NonNull Context context) {
return get();
}
@NonNull public static ShellManager get() {
if (sInstance == null) {
sInstance = new ShellManager();
}
return sInstance;
}
public ShellManager installBusyBox(@NonNull Context context) {
Installer.installBusyBox(context);
return this;
}
@Nullable public RootShell getRootShell() {
return getRootShell(false);
}
@Nullable public RootShell getRootShell(boolean newShell) {
RootShell rootShell;
if (!newShell && rootShells.size() > 0) {
rootShell = rootShells.get(0);
if (rootShell != null) {
return rootShell;
}
}
rootShell = createRootShell();
rootShells.add(rootShell);
return rootShell;
}
@Nullable private RootShell createRootShell() {
try {
return new RootShell();
} catch (IOException | TimeoutException | RootDeniedException e) {
if (ShellLogger.DEBUG) {
Log.e(TAG, "Error creating new root shell", e);
}
}
return null;
}
@Nullable public NormalShell getNormalShell() {
return getNormalShell(false);
}
@Nullable public NormalShell getNormalShell(boolean newShell) {
NormalShell normalShell;
if (!newShell && normalShells.size() > 0) {
normalShell = normalShells.get(0);
if (normalShell != null) {
return normalShell;
}
}
normalShell = createNormalShell();
normalShells.add(normalShell);
return normalShell;
}
@Nullable private NormalShell createNormalShell() {
try {
return new NormalShell();
} catch (IOException | TimeoutException | RootDeniedException e) {
if (ShellLogger.DEBUG) {
Log.e(TAG, "Error creating new shell", e);
}
}
return null;
}
public synchronized void cleanupRootShells() {
if (rootShells == null) {
rootShells = new ArrayList<>();
}
if (rootShells.size() > 0) {
final Iterator<RootShell> rootShellIterator = rootShells.iterator();
while (rootShellIterator.hasNext()) {
final RootShell rootShell = rootShellIterator.next();
rootShell.close();
rootShellIterator.remove();
}
rootShells.clear();
}
}
public synchronized void cleanupNormalShells() {
if (normalShells == null) {
normalShells = new ArrayList<>();
}
if (normalShells.size() > 0) {
final Iterator<NormalShell> normalShellIterator = normalShells.iterator();
while (normalShellIterator.hasNext()) {
final NormalShell normalShell = normalShellIterator.next();
normalShell.close();
normalShellIterator.remove();
}
normalShells.clear();
}
}
public synchronized int getNormalShellCount() {
return normalShells.size();
}
public synchronized int getRootShellCount() {
return rootShells.size();
}
public synchronized void cleanupShells() {
cleanupRootShells();
cleanupNormalShells();
}
public synchronized void onDestroy() {
cleanupShells();
}
}
| ShellManager: remove deprecated "get" method
Change-Id: Ic5938ed27b85f428da8325b2fc1e992feb2c8c05
Signed-off-by: Alexander Martinz <[email protected]>
| library/src/main/java/alexander/martinz/libs/execution/ShellManager.java | ShellManager: remove deprecated "get" method |
|
Java | mit | 809586c9a0f236ddfd329e2a2f072d1a077a68d8 | 0 | Jumper456/Chessboard,Jumper456/Chessboard | package net.yotvoo.chessboard;
import javafx.scene.layout.GridPane;
public class ChessBoard {
private ChessField[][] chessArray;
private ChessGame chessGame;
/*
* clickedField and clikedButton show which field/button has been clicked as the source field
* when the next click happens, it means to move the piece from this source
*/
private ChessField clickedField = null;
private ChessboardButton clickedButton = null;
/*
* chessButtonClicked should be invoked after the chessboard button is cliked.
* the concept is to click first the field with the piece you want to move and than click the target field
* gets the button clicked and the corresponding chessbaord field
* if there is no previous click recorded in clickedField variable, sets this variable
* if there is a previous click recorded, performs moving the piece to the field clicked as second
* if the previous click has been made at empty field does nothing
*/
void chessButtonClicked(ChessField chessField, ChessboardButton chessboardButton){
if ((clickedField == null) && (chessField.getPiece() != null)){
if (((chessField.getPiece().getPieceColor() == ChessPiece.PieceColor.WHITE)
&& chessGame.isWhiteMove())
|| ((chessField.getPiece().getPieceColor() == ChessPiece.PieceColor.BLACK)
&& !chessGame.isWhiteMove())){
clickedField = chessField;
clickedButton = chessboardButton;
System.out.println("first click set");
}
}
else{
/*
TODO Implement isMoveLegal methode and call it here
moving the code below to that methode
*/
// move the piece and change the white/black move flag
if (clickedField != null){
//check if not clicked the same piece twice
if (clickedField != chessField) {
//check if clicked empty or occupied field
if (chessField.getPiece() != null){
//check if attacked own or opponents piece
if (chessField.getPiece().getPieceColor() == clickedField.getPiece().getPieceColor())
System.out.println("Attacked own piece!");
else {
System.out.println("second click was valid move to occupied field");
movePieceTo(chessField, chessboardButton);
}
}
else{
System.out.println("second click was valid move to empty field");
movePieceTo(chessField, chessboardButton);
}
}
else
System.out.println("Illegal move - clicked the same field twice!");
}
else
System.out.println("Illegal move - now is opposite side move!");
}
}
void movePieceTo(ChessField chessField, ChessboardButton chessboardButton){
System.out.println("moving piece");
recordMove(clickedField, chessField);
chessField.setPiece(clickedField.getPiece());
if (chessGame.isWhiteMove()) {
chessGame.setWhiteMove(false);
} else {
chessGame.setWhiteMove(true);
}
clickedField.clearPiece();
printBoardAsString();
clickedButton.redraw();
chessboardButton.redraw();
clickedField = null;
}
void recordMove(ChessField sourceField, ChessField targetField){
String pieceSymbol = "X";
String sourceCoords = "Y0";
String targetCoords = "Z0";
String record = "record not initialized";
if (sourceField.getPiece() != null)
pieceSymbol = sourceField.getPiece().getSymbol();
else
pieceSymbol = "???";
sourceCoords = sourceField.getCoordinates();
targetCoords = targetField.getCoordinates();
record = "".concat(pieceSymbol).concat(sourceCoords).concat(targetCoords);
Main.addGameScriptEntry(record);
}
/*
* Constructor, initializes fields of the chessArray
*/
ChessBoard() {
chessArray = new ChessField[8][8];
chessGame = new ChessGame();
initializeFields();
}
/*
* prepares the chessArray filling it with the ChessField objects
* */
void prepareBoard(){
setStandardBordOrder();
}
private void initializeFields(){
int row;
int col;
for (row = 0; row <= 7; row++) {
for (col = 0; col <= 7; col++) {
chessArray[row][col] = new ChessField(this, row, col, chessCooordinate(row, col));
}
}
}
private String chessCooordinate(int row, int col){
return columnName(col+1) + (8-row);
}
//sets standard board pieces order on the board, does not clear any existing fields, expects the board to be empty
private void setStandardBordOrder(){
chessArray[0][0].setPiece(new ChessPiece(ChessPiece.PieceType.ROOK, ChessPiece.PieceColor.BLACK));
chessArray[0][1].setPiece(new ChessPiece(ChessPiece.PieceType.KNIGHT, ChessPiece.PieceColor.BLACK));
chessArray[0][2].setPiece(new ChessPiece(ChessPiece.PieceType.BISHOP, ChessPiece.PieceColor.BLACK));
chessArray[0][3].setPiece(new ChessPiece(ChessPiece.PieceType.QUEEN, ChessPiece.PieceColor.BLACK));
chessArray[0][4].setPiece(new ChessPiece(ChessPiece.PieceType.KING, ChessPiece.PieceColor.BLACK));
chessArray[0][5].setPiece(new ChessPiece(ChessPiece.PieceType.BISHOP, ChessPiece.PieceColor.BLACK));
chessArray[0][6].setPiece(new ChessPiece(ChessPiece.PieceType.KNIGHT, ChessPiece.PieceColor.BLACK));
chessArray[0][7].setPiece(new ChessPiece(ChessPiece.PieceType.ROOK, ChessPiece.PieceColor.BLACK));
chessArray[1][0].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][1].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][2].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][3].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][4].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][5].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][6].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][7].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[6][0].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][1].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][2].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][3].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][4].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][5].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][6].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][7].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[7][0].setPiece(new ChessPiece(ChessPiece.PieceType.ROOK, ChessPiece.PieceColor.WHITE));
chessArray[7][1].setPiece(new ChessPiece(ChessPiece.PieceType.KNIGHT, ChessPiece.PieceColor.WHITE));
chessArray[7][2].setPiece(new ChessPiece(ChessPiece.PieceType.BISHOP, ChessPiece.PieceColor.WHITE));
chessArray[7][3].setPiece(new ChessPiece(ChessPiece.PieceType.QUEEN, ChessPiece.PieceColor.WHITE));
chessArray[7][4].setPiece(new ChessPiece(ChessPiece.PieceType.KING, ChessPiece.PieceColor.WHITE));
chessArray[7][5].setPiece(new ChessPiece(ChessPiece.PieceType.BISHOP, ChessPiece.PieceColor.WHITE));
chessArray[7][6].setPiece(new ChessPiece(ChessPiece.PieceType.KNIGHT, ChessPiece.PieceColor.WHITE));
chessArray[7][7].setPiece(new ChessPiece(ChessPiece.PieceType.ROOK, ChessPiece.PieceColor.WHITE));
}
/**
* returns the current board (contained in the chessArray) as the string,
* this string contains the crlf to show separate rows of the board
* nonunicode letters show the pieces and free fields
*/
private String boardAsStringLetters(){
String myString = "";
int row;
int col;
for (row = 0; row <= 7; row++) {
for (col = 0; col <= 7; col++) {
if(chessArray[row][col].getPiece() != null) {
myString = myString.concat(chessArray[row][col].getPiece().getNameStr());
myString = myString.concat(chessArray[row][col].getPiece().getColorStr());
myString = myString.concat(" ");
}
else{
myString = myString.concat("-- ");
}
}
myString = myString.concat("\r\n");
}
return myString;
}
/**
* returns the current board (contained in the chessArray) as the string,
* this string contains the crlf to show separate rows of the board
* the unicode chess symbols are used to show the pieces and free fields
*/
private String boardAsStringSymbols(){
String myString = "";
int row;
int col;
for (row = 0; row <= 7; row++) {
for (col = 0; col <= 7; col++) {
if(chessArray[row][col].getPiece() != null) {
myString = myString.concat(chessArray[row][col].getPiece().getSymbol());
myString = myString.concat(" ");
}
else{
myString = myString.concat("\u26CB ");
}
}
myString = myString.concat("\r\n");
}
return myString;
}
//populates given grid pane with the current fields from chessArray
void populateGridPane(GridPane gridPane){
//String buttonText;
int row;
int col;
//fill the palyable fields
for (row = 0; row <= 7; row++) {
for (col = 0; col <= 7; col++) {
gridPane.add(new ChessboardButton(chessArray[row][col]), col + 1, row + 1);
}
}
//Fill the border fields with coordinates
ChessBorderButton button;
for (row = 1; row <= 8; row++) {
button = new ChessBorderButton("" + (9 - row),false);
gridPane.add( button , 0, row );
button = new ChessBorderButton("" + (9 - row),false);
gridPane.add( button, 9, row );
}
for (col = 1; col <= 8; col++) {
button = new ChessBorderButton(columnName(col),true);
gridPane.add( button, col , 0 );
button = new ChessBorderButton(columnName(col),true);
gridPane.add( button, col , 9 );
}
}
private String columnName(int columnNumber){
String name = "?";
switch (columnNumber){
case 1: name = "a";
break;
case 2: name = "b";
break;
case 3: name = "c";
break;
case 4: name = "d";
break;
case 5: name = "e";
break;
case 6: name = "e";
break;
case 7: name = "f";
break;
case 8: name = "g";
break;
}
return name;
}
//prints the board as the string to the standard out
void printBoardAsString(){
System.out.println(boardAsStringSymbols());
}
/*
//move the piece from the starting position to the target position
public boolean movePiece(int startRow, int startColumn, int targetRow, int targetColum){
return true;
}
*/
}
| src/net/yotvoo/chessboard/ChessBoard.java | package net.yotvoo.chessboard;
import javafx.scene.layout.GridPane;
public class ChessBoard {
private ChessField[][] chessArray;
private ChessGame chessGame;
/*
* clickedField and clikedButton show which field/button has been clicked as the source field
* when the next click happens, it means to move the piece from this source
*/
private ChessField clickedField = null;
private ChessboardButton clickedButton = null;
/*
* chessButtonClicked should be invoked after the chessboard button is cliked.
* the concept is to click first the field with the piece you want to move and than click the target field
* gets the button clicked and the corresponding chessbaord field
* if there is no previous click recorded in clickedField variable, sets this variable
* if there is a previous click recorded, performs moving the piece to the field clicked as second
* if the previous click has been made at empty field does nothing
*/
void chessButtonClicked(ChessField chessField, ChessboardButton chessboardButton){
if ((clickedField == null) && (chessField.getPiece() != null)){
if (((chessField.getPiece().getPieceColor() == ChessPiece.PieceColor.WHITE)
&& chessGame.isWhiteMove())
|| ((chessField.getPiece().getPieceColor() == ChessPiece.PieceColor.BLACK)
&& !chessGame.isWhiteMove())){
clickedField = chessField;
clickedButton = chessboardButton;
System.out.println("first click set");
}
}
else{
/*
TODO Implement isMoveLegal methode and call it here
moving the code below to that methode
*/
// move the piece and change the white/black move flag
if (clickedField != null){
//check if not clicked the same piece twice
if (clickedField != chessField) {
//check if clicked empty or occupied field
if (chessField.getPiece() != null){
//check if attacked own or opponents piece
if (chessField.getPiece().getPieceColor() == clickedField.getPiece().getPieceColor())
System.out.println("Attacked own piece!");
else {
System.out.println("second click was valid move to occupied field");
movePieceTo(chessField, chessboardButton);
}
}
else{
System.out.println("second click was valid move to empty field");
movePieceTo(chessField, chessboardButton);
}
}
else
System.out.println("Illegal move - clicked the same field twice!");
}
else
System.out.println("Illegal move - now is opposite side move!");
}
}
void movePieceTo(ChessField chessField, ChessboardButton chessboardButton){
System.out.println("moving piece");
recordMove(clickedField, chessField);
chessField.setPiece(clickedField.getPiece());
if (chessGame.isWhiteMove()) {
chessGame.setWhiteMove(false);
} else {
chessGame.setWhiteMove(true);
}
clickedField.clearPiece();
printBoardAsString();
clickedButton.redraw();
chessboardButton.redraw();
clickedField = null;
}
void recordMove(ChessField sourceField, ChessField targetField){
String pieceSymbol = "X";
String sourceCoords = "Y0";
String targetCoords = "Z0";
String record = "record not initialized";
if (sourceField.getPiece() != null)
pieceSymbol = sourceField.getPiece().getSymbol();
else
pieceSymbol = "???";
sourceCoords = sourceField.getCoordinates();
targetCoords = targetField.getCoordinates();
record = "".concat(pieceSymbol).concat(sourceCoords).concat(targetCoords);
Main.addGameScriptEntry(record);
}
/*
* Constructor, initializes fields of the chessArray
*/
ChessBoard() {
chessArray = new ChessField[8][8];
chessGame = new ChessGame();
initializeFields();
}
/*
* prepares the chessArray filling it with the ChessField objects
* */
void prepareBoard(){
setStandardBordOrder();
}
private void initializeFields(){
int row;
int col;
for (row = 0; row <= 7; row++) {
for (col = 0; col <= 7; col++) {
chessArray[row][col] = new ChessField(this, row, col, chessCooordinate(row, col));
}
}
}
private String chessCooordinate(int row, int col){
return columnName(col) + row;
}
//sets standard board pieces order on the board, does not clear any existing fields, expects the board to be empty
private void setStandardBordOrder(){
chessArray[0][0].setPiece(new ChessPiece(ChessPiece.PieceType.ROOK, ChessPiece.PieceColor.BLACK));
chessArray[0][1].setPiece(new ChessPiece(ChessPiece.PieceType.KNIGHT, ChessPiece.PieceColor.BLACK));
chessArray[0][2].setPiece(new ChessPiece(ChessPiece.PieceType.BISHOP, ChessPiece.PieceColor.BLACK));
chessArray[0][3].setPiece(new ChessPiece(ChessPiece.PieceType.QUEEN, ChessPiece.PieceColor.BLACK));
chessArray[0][4].setPiece(new ChessPiece(ChessPiece.PieceType.KING, ChessPiece.PieceColor.BLACK));
chessArray[0][5].setPiece(new ChessPiece(ChessPiece.PieceType.BISHOP, ChessPiece.PieceColor.BLACK));
chessArray[0][6].setPiece(new ChessPiece(ChessPiece.PieceType.KNIGHT, ChessPiece.PieceColor.BLACK));
chessArray[0][7].setPiece(new ChessPiece(ChessPiece.PieceType.ROOK, ChessPiece.PieceColor.BLACK));
chessArray[1][0].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][1].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][2].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][3].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][4].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][5].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][6].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[1][7].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.BLACK));
chessArray[6][0].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][1].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][2].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][3].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][4].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][5].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][6].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[6][7].setPiece(new ChessPiece(ChessPiece.PieceType.PAWN, ChessPiece.PieceColor.WHITE));
chessArray[7][0].setPiece(new ChessPiece(ChessPiece.PieceType.ROOK, ChessPiece.PieceColor.WHITE));
chessArray[7][1].setPiece(new ChessPiece(ChessPiece.PieceType.KNIGHT, ChessPiece.PieceColor.WHITE));
chessArray[7][2].setPiece(new ChessPiece(ChessPiece.PieceType.BISHOP, ChessPiece.PieceColor.WHITE));
chessArray[7][3].setPiece(new ChessPiece(ChessPiece.PieceType.QUEEN, ChessPiece.PieceColor.WHITE));
chessArray[7][4].setPiece(new ChessPiece(ChessPiece.PieceType.KING, ChessPiece.PieceColor.WHITE));
chessArray[7][5].setPiece(new ChessPiece(ChessPiece.PieceType.BISHOP, ChessPiece.PieceColor.WHITE));
chessArray[7][6].setPiece(new ChessPiece(ChessPiece.PieceType.KNIGHT, ChessPiece.PieceColor.WHITE));
chessArray[7][7].setPiece(new ChessPiece(ChessPiece.PieceType.ROOK, ChessPiece.PieceColor.WHITE));
}
/**
* returns the current board (contained in the chessArray) as the string,
* this string contains the crlf to show separate rows of the board
* nonunicode letters show the pieces and free fields
*/
private String boardAsStringLetters(){
String myString = "";
int row;
int col;
for (row = 0; row <= 7; row++) {
for (col = 0; col <= 7; col++) {
if(chessArray[row][col].getPiece() != null) {
myString = myString.concat(chessArray[row][col].getPiece().getNameStr());
myString = myString.concat(chessArray[row][col].getPiece().getColorStr());
myString = myString.concat(" ");
}
else{
myString = myString.concat("-- ");
}
}
myString = myString.concat("\r\n");
}
return myString;
}
/**
* returns the current board (contained in the chessArray) as the string,
* this string contains the crlf to show separate rows of the board
* the unicode chess symbols are used to show the pieces and free fields
*/
private String boardAsStringSymbols(){
String myString = "";
int row;
int col;
for (row = 0; row <= 7; row++) {
for (col = 0; col <= 7; col++) {
if(chessArray[row][col].getPiece() != null) {
myString = myString.concat(chessArray[row][col].getPiece().getSymbol());
myString = myString.concat(" ");
}
else{
myString = myString.concat("\u26CB ");
}
}
myString = myString.concat("\r\n");
}
return myString;
}
//populates given grid pane with the current fields from chessArray
void populateGridPane(GridPane gridPane){
//String buttonText;
int row;
int col;
//fill the palyable fields
for (row = 0; row <= 7; row++) {
for (col = 0; col <= 7; col++) {
gridPane.add(new ChessboardButton(chessArray[row][col]), col + 1, row + 1);
}
}
//Fill the border fields with coordinates
ChessBorderButton button;
for (row = 1; row <= 8; row++) {
button = new ChessBorderButton("" + (9 - row),false);
gridPane.add( button , 0, row );
button = new ChessBorderButton("" + (9 - row),false);
gridPane.add( button, 9, row );
}
for (col = 1; col <= 8; col++) {
button = new ChessBorderButton(columnName(col),true);
gridPane.add( button, col , 0 );
button = new ChessBorderButton(columnName(col),true);
gridPane.add( button, col , 9 );
}
}
private String columnName(int columnNumber){
String name = "?";
switch (columnNumber){
case 1: name = "A";
break;
case 2: name = "B";
break;
case 3: name = "C";
break;
case 4: name = "D";
break;
case 5: name = "E";
break;
case 6: name = "F";
break;
case 7: name = "G";
break;
case 8: name = "H";
break;
}
return name;
}
//prints the board as the string to the standard out
void printBoardAsString(){
System.out.println(boardAsStringSymbols());
}
/*
//move the piece from the starting position to the target position
public boolean movePiece(int startRow, int startColumn, int targetRow, int targetColum){
return true;
}
*/
}
| Bug fixed: bad coordinates has been given to chess field and recorded.
| src/net/yotvoo/chessboard/ChessBoard.java | Bug fixed: bad coordinates has been given to chess field and recorded. |
|
Java | mit | cc235cf6eaf7872b0f01bea7e116858f30e91662 | 0 | ReactionMechanismGenerator/RMG-Java,faribas/RMG-Java,keceli/RMG-Java,KEHANG/RMG-Java,keceli/RMG-Java,faribas/RMG-Java,nyee/RMG-Java,nyee/RMG-Java,ReactionMechanismGenerator/RMG-Java,enochd/RMG-Java,rwest/RMG-Java,keceli/RMG-Java,jwallen/RMG-Java,nyee/RMG-Java,ReactionMechanismGenerator/RMG-Java,enochd/RMG-Java,connie/RMG-Java,jwallen/RMG-Java,enochd/RMG-Java,KEHANG/RMG-Java,rwest/RMG-Java,nyee/RMG-Java,rwest/RMG-Java,rwest/RMG-Java,enochd/RMG-Java,KEHANG/RMG-Java,faribas/RMG-Java,jwallen/RMG-Java,rwest/RMG-Java,enochd/RMG-Java,KEHANG/RMG-Java,jwallen/RMG-Java,KEHANG/RMG-Java,jwallen/RMG-Java,connie/RMG-Java,ReactionMechanismGenerator/RMG-Java,nyee/RMG-Java,ReactionMechanismGenerator/RMG-Java,connie/RMG-Java,keceli/RMG-Java,nyee/RMG-Java,keceli/RMG-Java,connie/RMG-Java,enochd/RMG-Java,KEHANG/RMG-Java,jwallen/RMG-Java,keceli/RMG-Java,faribas/RMG-Java,connie/RMG-Java | ////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2011 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.chem;
import java.io.*;
import java.util.*;
import jing.chemUtil.*;
import jing.chemParser.*;
import jing.chemUtil.Arc;
import jing.chemUtil.Node;
import jing.chemUtil.Graph;
import jing.param.Global;
import jing.param.Temperature;
import jing.rxnSys.Logger;
import jing.rxnSys.ReactionModelGenerator;
//## package jing::chem
//----------------------------------------------------------------------------
// jing\chem\ChemGraph.java
//----------------------------------------------------------------------------
//## class ChemGraph
public class ChemGraph implements Matchable {
protected static int MAX_OXYGEN_NUM = 10; //20 Modified by AJ //## attribute MAX_OXYGEN_NUM
protected static int MAX_CARBON_NUM = 30;//100 Modified by AJ //SS
protected static int MAX_CYCLE_NUM = 10; //SS (no fused rings); gmagoon: to turn fused rings off, set this to 1 (will exclude multiple non-fused rings, as well, I think)
/**
Maximal radical number allowed in a ChemGraph.
*/
protected static int MAX_RADICAL_NUM = 10; //## attribute MAX_RADICAL_NUM
protected static int MAX_SILICON_NUM = 10;
protected static int MAX_SULFUR_NUM = 10;
protected static int MAX_HEAVYATOM_NUM = 100;
protected static String repOkString = null;
public static boolean useQM = false;//gmagoon 6/15/09: flag for thermo estimation using quantum results; there may be a better place for this (Global?) but for now, this should work
public static boolean useQMonCyclicsOnly=false;
/**
Chemical Formula of a ChemGraph.
*/
protected String chemicalFormula = null; //## attribute chemicalFormula
/**
The overall forbidden structure. When any new ChemGraph instance is generated, RMG check if it has any of the forbidden structure. If it has, it wont be generated.
*/
protected static HashSet forbiddenStructure = new HashSet(); //## attribute forbiddenStructure
protected int internalRotor = -1; //## attribute internalRotor
/**
A collection of all the possible symmetry Axis in a ChemGraph.
For example: the C=C=O skeleton in (CH3)2C=C=O
*/
//protected HashSet symmetryAxis = null; //## attribute symmetryAxis
/**
Symmetry number of a ChemGraph. Used in calculating entropy.
*/
protected int symmetryNumber = -1; //## attribute symmetryNumber
/**
It is a unique string representation for this chem structure. The method to generating it has not implemented yet.
*/
protected String uniqueString; //## attribute uniqueString
protected Graph graph;
protected Species species;
protected ThermoData thermoData;
protected AbramData abramData;
protected UnifacData unifacData;
protected GeneralGAPP thermoGAPP;
protected GeneralSolvationGAPP SolvationGAPP;
protected GeneralAbramGAPP abramGAPP;
protected GeneralUnifacGAPP unifacGAPP;
protected ThermoData solvthermoData;
protected TransportData transportData;
protected GATransportP transportGAPP;
protected boolean fromprimarythermolibrary = false;
protected boolean isAromatic = false;
protected String InChI;
protected String InChIKey;
protected String thermoComments = "";
protected String freqComments = "";
// Constructors
private ChemGraph() {
}
private ChemGraph(Graph p_graph) throws ForbiddenStructureException {
graph = p_graph;
// isAromatic = isAromatic();
if (isForbiddenStructure(p_graph,getRadicalNumber(),getOxygenNumber(),getCarbonNumber()) || getRadicalNumber() > MAX_RADICAL_NUM || getOxygenNumber() > MAX_OXYGEN_NUM || getCycleNumber() > MAX_CYCLE_NUM) {
//if (getRadicalNumber() > MAX_RADICAL_NUM || getOxygenNumber() > MAX_OXYGEN_NUM || getCycleNumber() > MAX_CYCLE_NUM) {
String message = "The molecular structure\n"+ p_graph.toString() + " is forbidden by "+whichForbiddenStructures(p_graph, getRadicalNumber(), getOxygenNumber(), getCycleNumber()) +"and not allowed.";
ThermoData themo_from_library = GATP.getINSTANCE().primaryLibrary.getThermoData(getGraph());
if ( themo_from_library != null) {
Logger.warning(message);
Logger.warning(String.format("But it's in the %s, so it will be allowed anyway.\n",themo_from_library.getSource() ));
// nb. the source String begins "Primary Thermo Library:"
}
else{
graph = null;
throw new ForbiddenStructureException(message);
}
}
this.determineAromaticityAndWriteBBonds();
}
public void determineAromaticityAndWriteBBonds() {
addMissingHydrogen();
// If there are no cycles, cannot be aromatic
if (graph.getCycleNumber() == 0) return;
// Check each cycle for aromaticity
for (Iterator cyclesIter = graph.getCycle().iterator(); cyclesIter.hasNext();) {
int piElectronsInCycle = 0;
LinkedList graphComps = (LinkedList)cyclesIter.next();
boolean[] hadPiElectrons = new boolean[graphComps.size()];
boolean cycleStartedWithNode = false;
for (int numComps=0; numComps<graphComps.size(); numComps++) {
GraphComponent gc = (GraphComponent)graphComps.get(numComps);
if (gc instanceof Node) {
if (numComps==0) cycleStartedWithNode = true;
Atom a = (Atom)((Node)gc).getElement();
if (a.isBiradical()) {
piElectronsInCycle += 2;
hadPiElectrons[numComps] = true;
}
else if (!a.isRadical()) {
Iterator neighbors = ((Node)gc).getNeighbor();
int usedValency = 0;
/*
* We count here the number of double bonds attached to a particular
* atom.
*
* We do this because we don't want that species with a
* Cdd type carbon atom, i.e. carbon bonded by two double bonds,
* is identified as being aromatic.
*
* Previously, a five-membered cyclic species, containing
* three double bonds with one Cdd carbon, would be perceived
* as aromatic since 3*2 = 6 "Pi" electrons were counted,
* and a cyclic structure was present.
*
* This patch, albeit not very general, counts the total
* number of double bonds for a particular atom. If a second
* double bond is detected, the pi-electron counter is not updated
* by adding two.
*
* This makes at least some chemical sence, as you could
* argue that the second pair electrons in the pi-bonds (perpendicular to the other
* pair of electrons) does not interact and conjugate with the
* pi electrons of other electrons.
*
*/
int number_of_double_bonds = 0;
while (neighbors.hasNext()) {
Arc nodeA= (Arc)neighbors.next();
double order = ((Bond)(nodeA.getElement())).getOrder();
if(order==2) number_of_double_bonds++;
if(number_of_double_bonds != 2)
usedValency += ((Bond)(nodeA.getElement())).getOrder();
}
if (a.getChemElement().getValency()-usedValency >= 2) {
piElectronsInCycle += 2;
hadPiElectrons[numComps] = true;
}
}
} else if (gc instanceof Arc) {
Bond b = (Bond)((Arc)gc).getElement();
/*
* For now, species with a triple bond conjugated to two double bonds
* would also contribute to the pi electron count. Hence, molecules
* such as benzyne (InChI=1S/C6H4/c1-2-4-6-5-3-1/h1-4H) would
* have a hueckel number of 6 and would then be perceived as aromatic.
*
* The atomtype of the triple bonded carbons (Ct) would be changed
* to Cb and hence an atom would be added afterwards, in a place
* where that would not possible.
*
* In order to avoid this problem, an if conditional is added that
* checks whether the iterated bond is a double bond. If not,
* contributions to the pi electron count are not taken into account.
*/
if(b.getOrder() == 2){
int bondPiElectrons = b.getPiElectrons();
if (bondPiElectrons > 0) {
piElectronsInCycle += bondPiElectrons;
hadPiElectrons[numComps] = true;
}
}
}
}
// Check if the # of piElectronsInCycle = 4*n+2 (Huckel's rule)
int huckelMagicNumber = 2;
boolean obeysHuckelRule = false;
while (piElectronsInCycle >= huckelMagicNumber) {
if (piElectronsInCycle == huckelMagicNumber) {
obeysHuckelRule = true;
break;
}
else huckelMagicNumber += 4;
}
if (!obeysHuckelRule) return;
// Check if each node (atom) contributed to pi electrons in cycle
for (int i=0; i<hadPiElectrons.length/2; i++) {
if (cycleStartedWithNode) {
if (!hadPiElectrons[2*i]) {
if (i==0) {
if (!hadPiElectrons[1] && !hadPiElectrons[hadPiElectrons.length-1]) return;
} else {
if (!hadPiElectrons[2*i-1] && !hadPiElectrons[2*i+1]) return;
}
}
}
else {
if (!hadPiElectrons[2*i+1]) {
if (i==hadPiElectrons.length-1) {
if (!hadPiElectrons[0] && !hadPiElectrons[hadPiElectrons.length-2]) return;
} else {
if (!hadPiElectrons[2*i] && !hadPiElectrons[2*i+2]) return;
}
}
}
}
// If we've reached here, our assumption is that the cycle is aromatic
isAromatic = true;
for (int numComps=0; numComps<graphComps.size(); numComps++) {
GraphComponent gc = (GraphComponent)graphComps.get(numComps);
if (gc instanceof Arc) {
Arc currentArc = (Arc)gc;
Bond currentBond = (Bond)currentArc.getElement();
currentArc.setElement(currentBond.changeBondToAromatic());
}
}
/**
* After the bonds that were previously defined as "S" or "D" bonds,
* have been renamed to "B" bonds,
* We have to re-perceive the atom type of the atoms in the adjacency list.
* This is done by re-iterating over all nodes and calling the
* Node.updateFgElement.
*
* If this is not done, the thermodynamic properties estimation
* will fail to assign Cb GAVs to those atoms perceived as aromatic.
*
*/
for (int numComps=0; numComps<graphComps.size(); numComps++) {
GraphComponent gc = (GraphComponent)graphComps.get(numComps);
if (gc instanceof Node) {
Node currentNode = (Node)gc;
currentNode.updateFgElement();//update the FgElement
}
}
}
}
/*private boolean isAromatic() {
//first see if it is cyclic
if (graph.getCycleNumber() == 0)
return false;
//if cyclic then iterate over all the cycles
Iterator cyclesIter = graph.getCycle();
while (cyclesIter.hasNext()){
LinkedList cycle = (LinkedList)cyclesIter.next();
boolean hasdoublebond = false;
boolean quarternaryAtom = false;
boolean monoRadical = false;
int unsaturatedCarbon =0 ;
for (int i=0; i<=cycle.size(); i++){
GraphComponent gc = (GraphComponent)cycle.get(i);
if (gc instanceof Arc){
if ( ((Bond)((Arc)gc).getElement()).isDouble())
hasdoublebond = true;
}
else {
Atom a = (Atom)((Node)gc).getElement();
// is it unsaturate Carbon
if (a.isCarbon() && !a.isRadical())
unsaturatedCarbon++;
//it is a monoradical
if (a.freeElectron.order == 1){
monoRadical = true;
return false;
}
//you have to check for SO2RR radical presence
///what is a quarternary atom...i will check
}
}
if (!hasdoublebond || unsaturatedCarbon > 1)
return false;
//first check if the ring has exocyclic pi bonds
for (int i=0; i<=cycle.size();i++){
GraphComponent gc = (GraphComponent)cycle.get(i);
if (gc instanceof Node){
Iterator neighbors = gc.getNeighbor();
while (neighbors.hasNext()){
Arc neighborArc = (Arc)neighbors.next();
}
}
}
}
}*/
/**
Requires:
Effects: saturate all the node atom's undefined valence by adding Hydrogen.
Modifies: this.graph.nodeList
*/
//## operation addMissingHydrogen()
public void addMissingHydrogen() {
//#[ operation addMissingHydrogen()
Atom H = Atom.make(ChemElement.make("H"), FreeElectron.make("0"));
Bond S = Bond.make("S");
LinkedHashMap addedH = new LinkedHashMap();
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
int val = (int)atom.getValency();
double bondOrder = 0;
Iterator neighbor_iter = node.getNeighbor();
while (neighbor_iter.hasNext()) {
Arc arc = (Arc)neighbor_iter.next();
Bond bond = (Bond)arc.getElement();
bondOrder += bond.getOrder();
}
// if (bondOrder > val) throw new InvalidConnectivityException();
// else if (bondOrder < val) {
// addedH.put(node, new Integer(val-bondOrder));
// }
if (bondOrder < val) {
addedH.put(node, new Integer(val-(int)(bondOrder+1.0e-8)));
}
}
Graph g = getGraph();
iter = addedH.keySet().iterator();
while (iter.hasNext()) {
Node node = (Node)iter.next();
int Hnum = ((Integer)addedH.get(node)).intValue();
for (int i=0;i<Hnum; i++) {
Node newNode = g.addNode(H);
g.addArcBetween(node, S, newNode);
}
node.updateFgElement();
}
return;
//#]
}
public static ChemGraph saturate(ChemGraph p_chemGraph) {
//#[ operation saturate(ChemGraph)
int max_radNum_molecule = ChemGraph.getMAX_RADICAL_NUM();
int max_radNum_atom = Math.min(8,max_radNum_molecule);
ChemGraph result = null;
try {
result = ChemGraph.copy(p_chemGraph);
}
catch (Exception e) {
Logger.logStackTrace(e);
Logger.critical(e.getMessage());
System.exit(0);
}
FreeElectron satuated = FreeElectron.make("0");
Atom H = Atom.make(ChemElement.make("H"),satuated);
Bond S = Bond.make("S");
Graph g = result.getGraph();
int nn = g.getHighestNodeID();
for (int i = 0 ; i < nn; i++) {
Node node = g.getNodeAt(i);
if (node != null) {
Atom atom = (Atom)node.getElement();
int HNum = atom.getRadicalNumber();
if (atom.isRadical()) {
Atom newAtom = new Atom(atom.getChemElement(),satuated);
node.setElement(newAtom);
node.updateFeElement();
for (int j = 0; j < HNum; j++) {
Node n = g.addNode(H);
g.addArcBetween(node,S,n);
}
node.updateFgElement();
}
}
}
return result;
/*
int max_radNum_molecule = ChemGraph.getMAX_RADICAL_NUM();
int max_radNum_atom = Math.min(8,max_radNum_molecule);
int [] idArray = new int[max_radNum_molecule];
Atom [] atomArray = new Atom[max_radNum_molecule];
Node [][] newnode = new Node[max_radNum_molecule][max_radNum_atom];
int radicalSite = 0;
Iterator iter = p_chemGraph.getNodeList();
FreeElectron satuated = FreeElectron.make("0");
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isRadical()) {
radicalSite ++;
// save the old radical atom
idArray[radicalSite-1] = node.getID().intValue();
atomArray[radicalSite-1] = atom;
// new a satuated atom and replace the old one
Atom newAtom = new Atom(atom.getChemElement(),satuated);
node.setElement(newAtom);
node.updateFeElement();
}
}
// add H to satuate chem graph
Atom H = Atom.make(ChemElement.make("H"),satuated);
Bond S = Bond.make("S");
for (int i=0;i<radicalSite;i++) {
Node node = p_chemGraph.getNodeAt(idArray[i]);
Atom atom = atomArray[i];
int HNum = atom.getRadicalNumber();
for (int j=0;j<HNum;j++) {
newnode[i][j] = g.addNode(H);
g.addArcBetween(node,S,newnode[i][j]);
}
node.updateFgElement();
}
*/
//#]
}
/**
Requires: acyclic ChemGraph
Effects: calculate and return the symmetry number centered at p_node atom
Modifies:
*/
//## operation calculateAtomSymmetryNumber(Node)
public int calculateAtomSymmetryNumber(Node p_node) {
//#[ operation calculateAtomSymmetryNumber(Node)
// note: acyclic structure!!!!!!!!!!!!!
int sn = 1;
// if no neighbor or only one neighbor, sigma = 1, return 1;
int neighborNumber = p_node.getNeighborNumber();
if (neighborNumber < 2) return sn;
Atom atom = (Atom)p_node.getElement();
Iterator neighbor_iter = p_node.getNeighbor();
FGElement fge = (FGElement)p_node.getFgElement();
if (!atom.isRadical()) {
// satuated atom symmetric number calculation
if (fge.equals(FGElement.make("Cs")) || fge.equals(FGElement.make("Sis"))) {
// Cs:
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
Arc a3 = (Arc)neighbor_iter.next();
Arc a4 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
if (p_node.isSymmetric(a1,a3)) {
if (p_node.isSymmetric(a1,a4)) {
// AAAA
sn *= 12;
}
else {
// AAAB
sn *= 3;
}
}
else {
if (p_node.isSymmetric(a1,a4)) {
// AAAB
sn *= 3;
}
else if (p_node.isSymmetric(a3,a4)) {
// AABB
sn *= 2;
}
else {
// AABC
}
}
}
else {
if (p_node.isSymmetric(a1,a3)) {
if (p_node.isSymmetric(a1,a4)) {
// AAAB
sn *= 3;
}
else if (p_node.isSymmetric(a2,a4)) {
// AABB
sn *= 2;
}
else {
// AABC
}
}
else if (p_node.isSymmetric(a2,a3)) {
if (p_node.isSymmetric(a1,a4)) {
// AABB
sn *= 2;
}
else if (p_node.isSymmetric(a2,a4)) {
// AAAB
sn *= 3;
}
else {
// AABC
}
}
else {
// AABC or ABCD
}
}
}
else if (fge.equals(FGElement.make("Os")) || fge.equals(FGElement.make("Ss"))) {
// Os:
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
sn *= 2;
}
}
else if (fge.equals(FGElement.make("Cdd")) || fge.equals(FGElement.make("Sidd"))) {
// Cdd:
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
sn *= 2;
}
}
}
else {
// radical symmetric number calculation
if (fge.equals(FGElement.make("Cs")) || fge.equals(FGElement.make("Sis"))) {
// only consider Cs. and Cs..
FreeElectron fe = atom.getFreeElectron();
if (fe.getOrder() == 1) {
// mono-radical Cs.
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
Arc a3 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
if (p_node.isSymmetric(a1,a3))
sn *= 6;
else
sn *= 2;
}
else {
if (p_node.isSymmetric(a1,a3) || p_node.isSymmetric(a2,a3))
sn *= 2;
}
}
else if (fe.getOrder() == 2) {
// bi-radical Cs..
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2))
sn *= 2;
}
}
}
return sn;
//#]
}
//takes the fragments and corresponding rotor nodes for each side of the rotor
public int calculateRotorSymmetryNumber(Node p_node1, Node p_node2) {
//first calculate the symmetry number for each fragment
int frag1sn=calculateRotorFragmentSymmetryNumber(p_node1);//will return 1, 2, or 3
int frag2sn=calculateRotorFragmentSymmetryNumber(p_node2);//will return 1, 2, or 3
if(frag1sn==3 || frag2sn==3){
if(frag1sn==3){
if(frag2sn==3) return 3; //example: ethane
else if (frag2sn==2) return 6; //example: toluene
else return 3; //frag2sn==1; example: methanol
}
else{//frag2sn==3 (and frag1sn!=3)
if (frag2sn==2) return 6;//see above
else return 3; //frag1sn==1; see above
}
}
else if(frag1sn==2 || frag2sn==2){
return 2; //see "full" code below
//if(frag1sn==2){
//if(frag2sn==2) return 2; //example: biphenyl
//else return 2; //frag2sn==1; example: phenol
//}
//else{//frag2sn==2 (and frag1sn=1)
//return 2;//see above
//}
}
//otherwise, both frag1sn and frag2sn equal 1
return 1;
}
//returns 1, 2, or 3 based on the rotor fragment and rotor node passed in
//code is based off of calculateAtomSymmetryNumber as the idea is similar, but we must be able to handle incomplete fragments, triple bonds, and aromatic structures
//code does not handle radicals at present
public int calculateRotorFragmentSymmetryNumber(Node p_node) {
Atom atom = (Atom)p_node.getElement();
Iterator neighbor_iter = p_node.getNeighbor();
FGElement fge = (FGElement)p_node.getFgElement();
if(atom.isRadical()){
Logger.critical("calculateRotorFragmentSymmetryNumber() does not support radical sites");
System.exit(0);
}
// if no neighbor or only one neighbor, sigma = 1, return 1;
int neighborNumber = p_node.getNeighborNumber();
if (neighborNumber < 2){
if(fge.equals(FGElement.make("Ct"))){//triple bond case
//find the end of the cumulated triple bond system
Node n1 = p_node;
LinkedHashSet axis = new LinkedHashSet();
Arc arc = (Arc)neighbor_iter.next();
axis.add(arc);
p_node = getToEndOfCumulatedTripleBondSystem(arc,p_node,axis);
//use the new, non-Ct node for subsequent calculations
fge = (FGElement)p_node.getFgElement();
neighbor_iter = p_node.getNeighbor();
fge = (FGElement)p_node.getFgElement();
}
else{//e.g. peroxides, alcohols, etc.
return 1;
}
}
if (fge.equals(FGElement.make("Cs")) || fge.equals(FGElement.make("Sis"))) {
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
Arc a3 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
if (p_node.isSymmetric(a1,a3))
return 3;//AAA*//e.g. methyl rotor
}
}
else if(fge.equals(FGElement.make("Cb")) || fge.equals(FGElement.make("Cbf"))){
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
return 2;//AA*//e.g. phenyl group
}
}
return 1;
}
/**
Requires: acyclic ChemGraph
Effects: calculate and return the symmetry number by all the possible symmetry axis in this ChemGraph.
Modifies:
*/
//## operation calculateAxisSymmetryNumber()
public int calculateAxisSymmetryNumber() {
//#[ operation calculateAxisSymmetryNumber()
int sn = 1;
// note: acyclic structure!!!!!!!!!!!!!
LinkedHashSet symmetryAxis = new LinkedHashSet();
Iterator iter = getArcList();
while (iter.hasNext()) {
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (bond.isDouble()&&!arc.getInCycle()) {//2/22/10 gmagoon: added check to make sure the arc is not in a cycle; hopefully this should prevent infinite recursion errors in getToEndOfAxis caused by cyclic species like cyclic, cumulenic C3 while still preserving the ability to estimate axis symmetry number for "cyclic" cases where the axis is not part of the cycle
Iterator neighbor_iter = arc.getNeighbor();
Node n1 = (Node)neighbor_iter.next();
Node n2 = (Node)neighbor_iter.next();
// FGElement Cd = FGElement.make("Cd");
FGElement Cdd = FGElement.make("Cdd");
// FGElement Sid = FGElement.make("Sid");
FGElement Sidd = FGElement.make("Sidd");
FGElement fge1 = (FGElement)n1.getFgElement();
FGElement fge2 = (FGElement)n2.getFgElement();
LinkedHashSet axis = new LinkedHashSet();
axis.add(arc);
if (fge1.equals(Cdd) || fge1.equals(Sidd)) n1 = getToEndOfAxis(arc,n1,axis);
if (fge2.equals(Cdd) || fge2.equals(Sidd)) n2 = getToEndOfAxis(arc,n2,axis);
Atom atom1 = (Atom)n1.getElement();
Atom atom2 = (Atom)n2.getElement();
if (atom1.isRadical() || atom2.isRadical()) return sn;
Bond D = Bond.make("D");
if (!symmetryAxis.contains(axis)) {
symmetryAxis.add(axis);
boolean l1 = n1.isLeaf();
boolean l2 = n2.isLeaf();
if (!l1 && !l2) {
Iterator i1 = n1.getNeighbor();
Iterator i2 = n2.getNeighbor();
Arc a1 = (Arc)i1.next();
if (((Bond)a1.getElement()).equals(D)) a1 = (Arc)i1.next();
Arc a2 = (Arc)i1.next();
if (((Bond)a2.getElement()).equals(D)) a2 = (Arc)i1.next();
Arc a3 = (Arc)i2.next();
if (((Bond)a3.getElement()).equals(D)) a3 = (Arc)i2.next();
Arc a4 = (Arc)i2.next();
if (((Bond)a4.getElement()).equals(D)) a4 = (Arc)i2.next();
if (n1.isSymmetric(a1,a2) && n2.isSymmetric(a3,a4)) {
sn *= 2;
}
}
else if (!l1 && l2) {
Iterator i = n1.getNeighbor();
Arc a1 = (Arc)i.next();
if (((Bond)a1.getElement()).equals(D)) a1 = (Arc)i.next();
Arc a2 = (Arc)i.next();
if (((Bond)a2.getElement()).equals(D)) a2 = (Arc)i.next();
if (n1.isSymmetric(a1,a2)) {
sn *= 2;
}
}
else if (l1 && !l2) {
Iterator i = n2.getNeighbor();
Arc a1 = (Arc)i.next();
if (((Bond)a1.getElement()).equals(D)) a1 = (Arc)i.next();
Arc a2 = (Arc)i.next();
if (((Bond)a2.getElement()).equals(D)) a2 = (Arc)i.next();
if (n2.isSymmetric(a1,a2)) {
sn *= 2;
}
}
}
}
}
return sn;
//#]
}
/**
Requires: acyclic ChemGraph
Effects: calculate and return the symmetry number centered at p_arc bond
Modifies:
*/
//## operation calculateBondSymmetryNumber(Arc)
public int calculateBondSymmetryNumber(Arc p_arc) {
//#[ operation calculateBondSymmetryNumber(Arc)
// note: acyclic structure!!!!!!!!!!!!!
int sn = 1;
// if no neighbor or only one neighbor, sigma = 1, return 1;
int neighborNumber = p_arc.getNeighborNumber();
if (neighborNumber != 2) throw new InvalidNeighborException("bond has " + neighborNumber + " neighbor!");
Bond bond = (Bond)p_arc.getElement();
Iterator neighbor_iter = p_arc.getNeighbor();
Node n1 = (Node)neighbor_iter.next();
Node n2 = (Node)neighbor_iter.next();
if (bond.isSingle() || bond.isDouble() || bond.isTriple()) {
if (p_arc.isSymmetric(n1,n2)) {
boolean opt = checkOpticalIsomer(p_arc);
if (!opt) sn *= 2;
}
}
return sn;
//#]
}
/**
Requires:
Effects: return Cp(T)
Modifies:
*/
//## operation calculateCp(Temperature)
public double calculateCp(Temperature p_temperature) {
//#[ operation calculateCp(Temperature)
return getThermoData().calculateCp(p_temperature);
//#]
}
/**
Requires:
Effects: calculate and return the symmetry number of the cyclic portion of this ChemGraph
Modifies:
svp
*/
//## operation calculateCyclicSymmetryNumber()
public int calculateCyclicSymmetryNumber(){
//#[ operation calculateCyclicSymmetryNumber()
int sn = 1;
LinkedList ring_structures = new LinkedList();//list of ring structures
LinkedList cycle_list = new LinkedList();//list of cycles
Iterator cycle_iter = getGraph().getCycle().iterator();
while (cycle_iter.hasNext()){
LinkedList current_cycle = (LinkedList)cycle_iter.next();
cycle_list.add(current_cycle);
}
//if 2 graph components share at least one cycle, they belong to the same ring structure
for (int i = 0; i <= cycle_list.size()-1; i++){
LinkedList current_ring = (LinkedList)cycle_list.get(i);
if (ring_structures.isEmpty()){
ring_structures.add(current_ring);
}
else{
int same_gc = 0;
Iterator ring_structure_iter = ring_structures.iterator();
Iterator current_ring_iter = current_ring.iterator();
while (ring_structure_iter.hasNext()){
LinkedList ring_structure = (LinkedList) ring_structure_iter.next();
while (current_ring_iter.hasNext()) {
GraphComponent gc = (GraphComponent) current_ring_iter.next();
if (ring_structure.contains(gc)) {
Iterator current_iter = current_ring.iterator();
while (current_iter.hasNext()){
GraphComponent current_gc = (GraphComponent)current_iter.next();
if (!ring_structure.contains(current_gc)){
ring_structure.add(current_gc);
ring_structures.set(ring_structures.indexOf(ring_structure), ring_structure);
}
}
same_gc++;
}
}
}
if (same_gc == 0){
ring_structures.add(current_ring);
}
}
if (i != cycle_list.size()-1){
for (int j = 1; j <= cycle_list.size()-1; j++){
LinkedList next_cycle = (LinkedList)cycle_list.get(j);
Iterator ring_structures_iter = ring_structures.iterator();
Iterator next_cycle_iter = next_cycle.iterator();
while (ring_structures_iter.hasNext()){
LinkedList current_ring_structure = (LinkedList)ring_structures_iter.next();
while (next_cycle_iter.hasNext()){
GraphComponent gc = (GraphComponent)next_cycle_iter.next();
if (current_ring_structure.contains(gc)){
Iterator ring_iter = next_cycle.iterator();
while(ring_iter.hasNext()){
GraphComponent current_gc = (GraphComponent)ring_iter.next();
if (!current_ring_structure.contains(current_gc)){
current_ring_structure.add(current_gc);
ring_structures.set(ring_structures.indexOf(current_ring_structure),current_ring_structure);
}
}
break;
}
}
}
}
}
}
Iterator iter = ring_structures.iterator();
while (iter.hasNext()){
LinkedList current_ring_structure = (LinkedList)iter.next();
Iterator gc_iter = current_ring_structure.iterator();
LinkedList node_list = new LinkedList(); //list of all cyclic nodes
LinkedList arc_list = new LinkedList(); //list of all cyclic arcs
while (gc_iter.hasNext()){
GraphComponent gc = (GraphComponent)gc_iter.next();
gc.setVisited(false);
if (gc instanceof Node){
node_list.add(gc);
}
else {
arc_list.add(gc);
}
}
//find all sets of equal nodes
LinkedList equal_node_list = new LinkedList();
for (int i = 0; i <= node_list.size() - 2; i++) {
Node current = (Node) node_list.get(i);
if (!current.isVisited()) {
LinkedList equal_list = new LinkedList(); //list of equivalent nodes
current.setVisited(true);
equal_list.add(current);
for (int j = i + 1; j <= node_list.size() - 1; j++) {
Node next = (Node) node_list.get(j);
Iterator list_iter = equal_list.iterator();
while (list_iter.hasNext()) {
current = (Node) list_iter.next();
if (isSymmetric(current, next)) {
equal_list.add(next);
next.setVisited(true);
break;
}
}
}
equal_node_list.add(equal_list); //add list of equivalent nodes to list of sets of equivalent nodes
}
}
//find all sets of equal arcs
LinkedList equal_arc_list = new LinkedList();
for (int i = 0; i <= arc_list.size() - 2; i++) {
Arc current = (Arc) arc_list.get(i);
if (!current.isVisited()) {
LinkedList equal_list = new LinkedList(); //list of equivalent arcs
current.setVisited(true);
equal_list.add(current);
for (int j = i + 1; j <= arc_list.size() - 1; j++) {
Arc next = (Arc) arc_list.get(j);
Iterator list_iter = equal_list.iterator();
while (list_iter.hasNext()) {
current = (Arc) list_iter.next();
if (isSymmetric(current, next)) {
equal_list.add(next);
next.setVisited(true);
break;
}
}
}
equal_arc_list.add(equal_list); //add list of equivalent arcs to list of sets of equivalent arcs
}
}
//find largest set of equal nodes
int node_sn = 1;
Iterator node_list_iter = equal_node_list.iterator();
while (node_list_iter.hasNext()) {
LinkedList current = (LinkedList) node_list_iter.next();
if (current.size() > node_sn) {
node_sn = current.size(); //node symmetry number = size of largest set of equivalent nodes
}
}
//find largest set of equal arcs
int arc_sn = 1;
Iterator arc_list_iter = equal_arc_list.iterator();
while (arc_list_iter.hasNext()) {
LinkedList current = (LinkedList) arc_list_iter.next();
if (current.size() > arc_sn) {
arc_sn = current.size(); //arc symmetry number = size of largest set of equivalent arcs
}
}
if (node_sn == node_list.size() && arc_sn == arc_list.size()) { //all nodes equal and all arcs equal
sn *= node_sn;
sn *= 2;
Node first_node = (Node)node_list.getFirst();
FGElement fge = (FGElement)first_node.getFgElement();
if (fge.equals(FGElement.make("Cs"))){
LinkedList acyclic_neighbor = new LinkedList();
Iterator neighbor_iter = first_node.getNeighbor();
while (neighbor_iter.hasNext()){
Arc arc = (Arc)neighbor_iter.next();
if (!arc.getInCycle()){
acyclic_neighbor.add(arc);
}
}
if (acyclic_neighbor.size() == 2){
Arc a1 = (Arc) acyclic_neighbor.getFirst();
Arc a2 = (Arc) acyclic_neighbor.getLast();
if (!first_node.isSymmetric(a1, a2)) {
sn /= 2;
}
}
}
}
else {
if (node_sn >= arc_sn) {
sn *= node_sn;
}
else {
sn *= arc_sn;
}
}
//if (sn >= 2 && sn%2 == 0){//added by Sally for non-planar PAH's
//sn = correctSymmetryNumber(sn);
//}
}
graph.setCycle(null);
graph.formSSSR();
return sn;
//#]
}
/**
Requires:
Effects: return G(T)
Modifies:
*/
//## operation calculateG(Temperature)
public double calculateG(Temperature p_temperature) {
//#[ operation calculateG(Temperature)
return getThermoData().calculateG(p_temperature);
//#]
}
/**
Requires:
Effects:return H(T)
Modifies:
*/
//## operation calculateH(Temperature)
public double calculateH(Temperature p_temperature) {
//#[ operation calculateH(Temperature)
return getThermoData().calculateH(p_temperature);
//#]
}
//## operation calculateInternalRotor()
public void calculateInternalRotor() {
//#[ operation calculateInternalRotor()
// add more check for resonance axis!!
int rotor = 0;
Graph g = getGraph();
for (Iterator iter = g.getArcList(); iter.hasNext();) {
Arc a = (Arc)iter.next();
Bond bond = (Bond)a.getElement();
if (bond.isSingle() && !a.getInCycle()) {
Iterator atomIter = a.getNeighbor();
Node n1 = (Node)atomIter.next();
Node n2 = (Node)atomIter.next();
if (!n1.isLeaf() && !n2.isLeaf()) {
rotor++;
}
}
}
internalRotor = rotor;
//#]
}
//uses same algorithm as calculate internal rotor, but stores the two atoms involved in the rotor and all the atoms on one side of the rotor (specifically, the side corresponding to the 2nd atom of the rotor)
//the information is returned in a LinkedHashMap where the Key is an array of [atom0 atom1 atom2 atom3] (with atom1 and atom2 being the "rotor atoms" and the others being the dihedral atoms) and the value is a Collection of atoms IDs associated with atom2
//note that at this stage, there is no check to make sure that the dihedral atoms are not collinear
public LinkedHashMap getInternalRotorInformation(){
LinkedHashMap rotorInfo = new LinkedHashMap();
Graph g = getGraph();
for (Iterator iter = g.getArcList(); iter.hasNext();) {
Arc a = (Arc)iter.next();
Bond bond = (Bond)a.getElement();
if (bond.isSingle() && !a.getInCycle()) {
Iterator atomIter = a.getNeighbor();
Node n1 = (Node)atomIter.next();
Node n2 = (Node)atomIter.next();
if (!n1.isLeaf() && !n2.isLeaf()) {
//rotor++;
//above here is the rotor identification algorithm; below here is the code that stores the necessary information about the rotor
Graph f=Graph.copy(g);//copy the graph so we don't modify the original
f.removeArc(f.getArcBetween(n1.getID(), n2.getID()));//this should separate the graph into disconnected pieces (unless it is part of a cycle; if it is part of a cycle, however, this section of code shouldn't be reached)
LinkedList pieces = f.partitionWithPreservedIDs();//partition into the two separate graphs
Graph sideA = (Graph)pieces.getFirst();
Graph sideB = (Graph)pieces.getLast();
//look for the piece that has node2
if(sideA.getNodeIDs().contains(n2.getID())){
Node atom1 = sideB.getNodeAt(n1.getID());
Node atom2 = sideA.getNodeAt(n2.getID());
Node dihedral1 = (Node)atom1.getNeighboringNodes().iterator().next();//get a neighboring node
Node dihedral2 = (Node)atom2.getNeighboringNodes().iterator().next();//get a neighboring node
int rotorSym = calculateRotorSymmetryNumber(atom1,atom2);
int[] rotorAtoms = {dihedral1.getID(), n1.getID(), n2.getID(), dihedral2.getID(), rotorSym};
rotorInfo.put(rotorAtoms, sideA.getNodeIDs());
}
else if (sideB.getNodeIDs().contains(n2.getID())){
Node atom1 = sideA.getNodeAt(n1.getID());
Node atom2 = sideB.getNodeAt(n2.getID());
Node dihedral1 = (Node)atom1.getNeighboringNodes().iterator().next();//get a neighboring node
Node dihedral2 = (Node)atom2.getNeighboringNodes().iterator().next();//get a neighboring node
int rotorSym = calculateRotorSymmetryNumber(atom1,atom2);
int[] rotorAtoms = {dihedral1.getID(), n1.getID(), n2.getID(), dihedral2.getID(), rotorSym};
rotorInfo.put(rotorAtoms, sideB.getNodeIDs());
}
else{
Logger.critical("Error in getInternalRotorInformation(): Cannot find node "+ n2.getID()+" after splitting from "+ n1.getID() +" in the following graph:\n"+ g.toString());
System.exit(0);
}
}
}
}
return rotorInfo;
}
// ## operation isLinear()
public boolean isLinear() {
//#[ operation isLinear()
// only check for linearity in molecules with at least two atoms
if (getAtomNumber() == 1) return false;
// cyclic molecules are not linear
if (!isAcyclic()) return false;
// biatomic molecules are always linear
if (getAtomNumber() == 2) return true;
// molecules with only double bonds are linear (e.g. CO2)
boolean allDouble = true;
Iterator iter = getArcList();
while (iter.hasNext()) {
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (!bond.isDouble()) allDouble = false;
}
if (allDouble) return true;
// molecule with alternating single and triple bonds are linear (e.g. acetylene)
boolean alternatingSingleTriple = true;
Iterator node_iter = getNodeList();
while (node_iter.hasNext()) {
Node node = (Node)node_iter.next();
int neighborNumber = node.getNeighborNumber();
if (neighborNumber == 2) {
Iterator neighbor_iter = node.getNeighbor();
Arc a1 = (Arc)neighbor_iter.next();
Bond b1 = (Bond)a1.getElement();
Arc a2 = (Arc)neighbor_iter.next();
Bond b2 = (Bond)a2.getElement();
if (! ((b1.isTriple() && b2.isSingle()) || (b1.isSingle() && b2.isTriple())))
alternatingSingleTriple = false;
}
else if (neighborNumber > 2)
alternatingSingleTriple = false;
}
if (alternatingSingleTriple) return true;
// if none of the above are true, it's nonlinear
return false;
//#]
}
/**
Requires:
Effects: return S(T)
Modifies:
*/
//## operation calculateS(Temperature)
public double calculateS(Temperature p_temperature) {
//#[ operation calculateS(Temperature)
return getThermoData().calculateS(p_temperature);
//#]
}
//## operation calculateSymmetryNumber()
public int calculateSymmetryNumber() {
//#[ operation calculateSymmetryNumber()
try {
getGraph().formSSSR();//svp
int sn = 1;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
if (!node.getInCycle()){//svp
sn *= calculateAtomSymmetryNumber(node);
}
}
iter = getArcList();
while (iter.hasNext()) {
Arc arc = (Arc)iter.next();
if (!arc.getInCycle()){//svp
sn *= calculateBondSymmetryNumber(arc);
}
}
sn *= calculateAxisSymmetryNumber();
if (!isAcyclic()) {//svp
sn *= calculateCyclicSymmetryNumber();
}
symmetryNumber = sn;
return sn;
}
catch (ClassCastException e) {
throw new InvalidChemGraphException();
}
//#]
}
/**
Requies:
Effects: check if p_arc bond is the single bond between two Oxygens, which is considered as optical isomers
Modifies:
*/
//## operation checkOpticalIsomer(Arc)
public boolean checkOpticalIsomer(Arc p_arc) {
//#[ operation checkOpticalIsomer(Arc)
// check if the p_arc is -O-O-
Bond b = (Bond)p_arc.getElement();
if (b.isSingle()) {
Iterator neighbor_iter = p_arc.getNeighbor();
Node n1 = (Node)neighbor_iter.next();
Node n2 = (Node)neighbor_iter.next();
Atom a1 = (Atom)n1.getElement();
Atom a2 = (Atom)n2.getElement();
FGElement fge1 = (FGElement)n1.getFgElement();
FGElement fge2 = (FGElement)n2.getFgElement();
if (!a1.isRadical() && fge1.equals(FGElement.make("Os")) && !a2.isRadical() && fge2.equals(FGElement.make("Os"))) {
return true;
}
// else if (!a1.isRadical() && fge1.equals(FGElement.make("Sis")) && !a2.isRadical() && fge2.equals(FGElement.make("Sis"))) {
// return true;
// }
}
return false;
//#]
}
/**
Requires:
Effects: clear the central node list
Modifies:
*/
//## operation clearCentralNode()
public void clearCentralNode() {
//#[ operation clearCentralNode()
getGraph().clearCentralNode();
//#]
}
/**
Requires:
Effects: return a new instance identical to this ChemGraph
Modifies:
*/
//## operation copy(ChemGraph)
public static ChemGraph copy(ChemGraph p_chemGraph) throws ForbiddenStructureException {
Graph g = Graph.copy(p_chemGraph.getGraph());
ChemGraph cg = new ChemGraph(g);
cg.uniqueString = p_chemGraph.getUniqueString();
cg.chemicalFormula = p_chemGraph.getChemicalFormula();
cg.species = p_chemGraph.getSpecies();
cg.symmetryNumber = p_chemGraph.symmetryNumber;
cg.thermoData = p_chemGraph.thermoData;
cg.thermoGAPP = p_chemGraph.thermoGAPP;
cg.InChI = p_chemGraph.InChI;
cg.internalRotor = p_chemGraph.internalRotor;
cg.solvthermoData = p_chemGraph.solvthermoData;
/*HashSet oldSymmetryAxis = p_chemGraph.getSymmetryAxis();
if (oldSymmetryAxis != null) {
cg.symmetryAxis = new HashSet();
for (Iterator iAxis = oldSymmetryAxis.iterator(); iAxis.hasNext(); ) {
HashSet newAxis = new HashSet();
HashSet oldAxis = (HashSet)iAxis.next();
for (Iterator iArc = oldAxis.iterator(); iArc.hasNext(); ) {
Arc arc = (Arc)iArc.next();
Iterator iNode = arc.getNeighbor();
int n1 = ((Node)iNode.next()).getID().intValue();
int n2 = ((Node)iNode.next()).getID().intValue();
Arc newArc = cg.getArcBetween(n1,n2);
newAxis.add(newArc);
}
cg.symmetryAxis.add(newAxis);
}
}*/
return cg;
}
/**
Requires:
Effects: return true iff two chemgraph have equivalent graph structures
Modifies:
*/
//## operation equals(Object)
public boolean equals(Object p_chemGraph) {
//#[ operation equals(Object)
if (this == p_chemGraph) return true;
return isEquivalent((ChemGraph)p_chemGraph);
//#]
}
/**
Requires:
Effects: generate the chemical formula of this chem graph and return it. if the graph is not initialized, return null.
Modifies:
*/
//## operation generateChemicalFormula()
public String generateChemicalFormula() {
//#[ operation generateChemicalFormula()
if (getGraph() == null) return null;
/*int cap = ChemElementDictionary.size();
Vector type = new Vector(cap);
int[] number = new int[cap];
*/
int C_number = 0;
int H_number = 0;
int O_number = 0;
int radical = 0;
// Added by MRH on 18-Jun-2009
// Hardcoding Si and S into RMG-java
int Si_number = 0;
int S_number = 0;
int Cl_number = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
radical += atom.getRadicalNumber();
if (atom.isCarbon()) {
C_number++;
}
else if (atom.isHydrogen()) {
H_number++;
}
else if (atom.isOxygen()) {
O_number++;
}
// Added by MRH on 18-Jun-2009
// Hardcoding Si and S into RMG-java
else if (atom.isSilicon()) {
Si_number++;
}
else if (atom.isSulfur()) {
S_number++;
}
else if (atom.isChlorine()) {
Cl_number++;
}
else {
throw new InvalidChemNodeElementException();
}
}
String s = "";
if (C_number>0) {
s = s + "C";
if (C_number >1) {
s = s + String.valueOf(C_number);
}
}
if (H_number>0) {
s = s + "H";
if (H_number >1) {
s = s + String.valueOf(H_number);
}
}
if (O_number>0) {
s = s + "O";
if (O_number >1) {
s = s + String.valueOf(O_number);
}
}
// Added by MRH on 18-Jun-2009
// Hardcoding Si and S into RMG-java
if (Si_number>0) {
s += "Si";
if (Si_number>1) {
s += String.valueOf(Si_number);
}
}
if (S_number>0) {
s += "S";
if (S_number>1) {
s += String.valueOf(S_number);
}
}
chemicalFormula = s;
if (radical == 1) {
chemicalFormula = chemicalFormula + "J";
}
else if (radical == 2) {
chemicalFormula = chemicalFormula + "JJ";
}
else if (radical == 3) {
chemicalFormula = chemicalFormula + "JJJ";
}
return chemicalFormula;
//#]
}
//6/9/09 gmagoon: modified to also generate InChIKey; see comments in corresponding Species function
public String [] generateInChI() {
String [] result = Species.generateInChI(this);
InChI = result[0];
InChIKey = result[1];
return result;
}
public String generateMolFileString() {
String mfs = Species.generateMolFileString(this,4);//use 4 for benzene bond type...this is apparently not part of MDL MOL file spec, but seems to be more-or-less of a de facto standard, and seems to be properly processed by RDKit (cf. http://sourceforge.net/mailarchive/forum.php?forum_name=inchi-discuss&max_rows=25&style=nested&viewmonth=200909 )
//note that for aromatic radicals (e.g. phenyl), this produces an RDKit error, as shown below (at least using the (somewhat old) RDKit on gmagoon's laptop as of 9/12/11), but it still seems to process correctly, though the guess geometry isn't that great (more like sp3 than sp2); in practice, we won't often be using radicals with RDKit (exceptions include when requested by user or in DictionaryReader), so this shouldn't be a big deal
//ERROR: Traceback (most recent call last):
//ERROR: File "c:\Users\User1\RMG-Java/scripts/distGeomScriptMolLowestEnergyConf.py", line 13, in <module>
//ERROR: AllChem.EmbedMultipleConfs(m, attempts,randomSeed=1)
//ERROR: Boost.Python.ArgumentError: Python argument types in
//ERROR: rdkit.Chem.rdDistGeom.EmbedMultipleConfs(NoneType, int)
//ERROR: did not match C++ signature:
//ERROR: EmbedMultipleConfs(class RDKit::ROMol {lvalue} mol, unsigned int numConfs=10, unsigned int maxAttempts=0, int randomSeed=-1, bool clearConfs=True, bool useRandomCoords=False, double boxSizeMult=2.0, bool randNegEig=True, unsigned int numZeroFail=1, double pruneRmsThresh=-1.0, class boost::python::dict {lvalue} coordMap={})
//an alternative would be to use bond type of 1, which also seems to work, though the guess geometry for non-radicals (e.g. benzene) is not great (sp3 hybridized rather than sp2 hybridized)
return mfs;
}
/**
Requires:
Effects: if the thermoGAPP is not set, set default GAPP. Use it to calculate the thermoData of this chem graph. if there is any exception during this process, throw FailGenerateThermoDataException.
Modifies: this.thermoData
*/
//## operation generateThermoData()
public ThermoData generateThermoData() throws FailGenerateThermoDataException {
//#[ operation generateThermoData()
// use GAPP to generate Thermo data
try {
if (useQM){
if(useQMonCyclicsOnly && this.isAcyclic()) thermoGAPP=GATP.getINSTANCE();//use GroupAdditivity for acyclic compounds if this option is set
else thermoGAPP=QMTP.getINSTANCE();
}
else if (thermoGAPP == null) setDefaultThermoGAPP();
thermoData = thermoGAPP.generateThermoData(this);
//fall back to GATP if it is a failed QMTP calculation
if (((String)thermoData.getSource()).equals("***failed calculation***")){
Logger.warning("Falling back to group additivity due to repeated failure in QMTP calculations");
thermoData=(GATP.getINSTANCE()).generateThermoData(this);
}
//thermoData = thermoGAPP.generateAbramData(this);
return thermoData;
}
catch (MultipleGroupFoundException e) {
throw e;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new FailGenerateThermoDataException();
}
//#]
}
public TransportData generateTransportData() {
if (transportGAPP == null) setDefaultTransportGAPP();
transportData = transportGAPP.generateTransportData(this);
return transportData;
}
// Amrit Jalan 05/09/2009
public ThermoData generateSolvThermoData() throws FailGenerateThermoDataException {
// use GAPP to generate Thermo data
try {
if (SolvationGAPP == null) setDefaultSolvationGAPP();
solvthermoData = SolvationGAPP.generateSolvThermoData(this);
return solvthermoData;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new FailGenerateThermoDataException();
}
}
public AbramData generateAbramData() throws FailGenerateThermoDataException {
// use GAPP to generate Thermo data
try {
if (abramGAPP == null) setDefaultAbramGAPP();
abramData = abramGAPP.generateAbramData(this);
return abramData;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new FailGenerateThermoDataException();
}
}
public UnifacData generateUnifacData() throws FailGenerateThermoDataException {
try {
if (unifacGAPP == null) setDefaultUnifacGAPP();
unifacData = unifacGAPP.generateUnifacData(this);
return unifacData;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new FailGenerateThermoDataException();
}
}
/**
Requires:
Effects: return the Arc between two positions in this ChemGraph
Modifies:
*/
public Arc getArcBetween(int p_position1, int p_position2) {
return getGraph().getArcBetween(p_position1,p_position2);
}
/**
Requires:
Effects: return an arc iterator of this ChemGraph
Modifies:
*/
//## operation getArcList()
public Iterator getArcList() {
//#[ operation getArcList()
return getGraph().getArcList();
//#]
}
/**
Requires:
Effects: return the atom at the p_position in this chem graph; if p_position is empty, return null;
Modifies:
*/
//## operation getAtomAt(int)
public Atom getAtomAt(int p_position) throws EmptyAtomException {
//#[ operation getAtomAt(int)
try {
return (Atom)(getNodeAt(p_position).getElement());
}
catch (NotInGraphException e) {
return null;
}
//#]
}
/**
Requires:
Effects: return the total atom number in this ChemGraph.
Modifies:
*/
//## operation getAtomNumber()
public int getAtomNumber() {
//#[ operation getAtomNumber()
return getGraph().getNodeNumber();
//#]
}
/**
Requires:
Effects: if there is a bond connecting p_position1 and p_position2, return that bond; otherwise, return null.
Modifies:
*/
//## operation getBondBetween(int,int)
public Bond getBondBetween(int p_position1, int p_position2) throws EmptyAtomException {
//#[ operation getBondBetween(int,int)
try {
return (Bond)(getArcBetween(p_position1,p_position2).getElement());
}
catch (ClassCastException e) {
return null;
}
//#]
}
//## operation getCarbonNumber()
public int getCarbonNumber() {
//#[ operation getCarbonNumber()
int cNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isCarbon()) {
cNum++;
}
}
return cNum;
//#]
}
/**
Requires:
Effects: return the hashMap of centralNode in this ChemGraph
Modifies:
*/
//## operation getCentralNode()
public LinkedHashMap getCentralNode() {
//#[ operation getCentralNode()
return getGraph().getCentralNode();
//#]
}
/**
Requires:
Effects: return the node whose centralID equals p_position
Modifies:
*/
//## operation getCentralNodeAt(int)
public Node getCentralNodeAt(int p_position) {
//#[ operation getCentralNodeAt(int)
return getGraph().getCentralNodeAt(p_position);
//#]
}
/**
Requires:
Effects: return the number of the central nodes in this chem graph
Modifies:
*/
//## operation getCentralNodeNumber()
public int getCentralNodeNumber() {
//#[ operation getCentralNodeNumber()
return getGraph().getCentralNodeNumber();
//#]
}
//## operation getChemicalFormula()
public String getChemicalFormula() {
//#[ operation getChemicalFormula()
if (chemicalFormula == null || chemicalFormula.length() == 0) generateChemicalFormula();
return chemicalFormula;
//#]
}
/**
Requires:
Effects: return the iterator loop over the graph's cycle list.
Modifies:
*/
//## operation getCycle()
public Iterator getCycle() {
//#[ operation getCycle()
return getGraph().getCycle().iterator();
//#]
}
public int getCycleNumber(){
return getGraph().getCycleNumber();
}
//## operation getHydrogenNumber()
public int getHydrogenNumber() {
//#[ operation getHydrogenNumber()
int hNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isHydrogen()) {
hNum++;
}
}
return hNum;
//#]
}
public String getInChI() {
if (InChI == null || InChI.length() == 0) generateInChI();
return InChI;
}
public String getInChIKey() {
if (InChIKey == null || InChIKey.length() == 0) generateInChI();
return InChIKey;
}
//gmagoon 7/25/09: same as above function, except it will replace an existing InChI; this is useful when ChemGraph changes (e.g. during HBI process)
public String getInChIAnew() {
generateInChI();
return InChI;
}
//gmagoon 7/25/09: same as above function, except it will replace an existing InChIKey; this is useful when ChemGraph changes (e.g. during HBI process)
public String getInChIKeyAnew() {
generateInChI();
return InChIKey;
}
//gmagoon 9/1/09: these functions (getModifiedInChIAnew and getModifiedInChIKeyAnew) do the same as above, except return a modified version of the InChI and InChIKey with an indication of the multiplicity based on the number of radicals if the number of radicals is 2 or greater
public String getModifiedInChIAnew(){
generateInChI();
String newInChI=null;
int radicalNumber = this.getUnpairedRadicalNumber();
// System.out.println("Radical number:"+radicalNumber);//for debugging purposes
if (radicalNumber >= 2){
newInChI = InChI.concat("/mult"+(radicalNumber+1));
}
else{
newInChI = InChI;
}
return newInChI;
}
public String getModifiedInChIKeyAnew(){
generateInChI();
String newInChIKey=null;
int radicalNumber = this.getUnpairedRadicalNumber();
// System.out.println("Radical number:"+radicalNumber);//for debugging purposes
if (radicalNumber >= 2){
newInChIKey = InChIKey.concat("mult"+(radicalNumber+1));
}
else{
newInChIKey= InChIKey;
}
return newInChIKey;
}
/**
Requires:
Effects: add the weight of all the atoms in this graph to calculate the molecular weight of this chem graph
Modifies:
*/
//## operation getMolecularWeight()
public double getMolecularWeight() {
//#[ operation getMolecularWeight()
double MW = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
MW += ((Atom)(node.getElement())).getWeight();
}
return MW;
//#]
}
/**
Requires:
Effects: return the "legal" name of this ChemGraph. The order of priority
(1) uniqueString
(2) species.name
(3) chemicalFormula
Modifies:
*/
//## operation getName()
public String getName() {
//#[ operation getName()
if (uniqueString != null && uniqueString.length() > 0) return uniqueString;
String name = getSpecies().getName();
if (name != null && name.length() > 0) return name;
return getChemicalFormula();
//#]
}
/**
Requires:
Effects: return the node whose ID equals p_position.
Modifies:
*/
//## operation getNodeAt(int)
public Node getNodeAt(int p_position) {
//#[ operation getNodeAt(int)
return getGraph().getNodeAt(p_position);
//#]
}
/**
Requires:
Effects: return the node whose ID equals p_ID.
Modifies:
*/
//## operation getNodeAt(Integer)
public Node getNodeAt(Integer p_ID) {
//#[ operation getNodeAt(Integer)
return getGraph().getNodeAt(p_ID);
//#]
}
/**
Requires:
Effects: return an iterator over the node collection of this graph
Modifies:
*/
//## operation getNodeList()
public Iterator getNodeList() {
//#[ operation getNodeList()
return getGraph().getNodeList();
//#]
}
public int getDoubleBonds(){
int dBond = 0;
Iterator iter = getArcList();
while (iter.hasNext()){
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (bond.order==2){
dBond++;
}
}
return dBond;
}
public int getSingleBonds(){
int sBond = 0;
Iterator iter = getArcList();
while (iter.hasNext()){
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (bond.order==1){
sBond++;
}
}
return sBond;
}
public int getTripleBonds(){
int tBond = 0;
Iterator iter = getArcList();
while (iter.hasNext()){
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (bond.order==3){
tBond++;
}
}
return tBond;
}
//## operation getOxygenNumber()
public int getOxygenNumber() {
//#[ operation getOxygenNumber()
int oNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isOxygen()) {
oNum++;
}
}
return oNum;
//#]
}
/**
Requires:
Effects: return a collection of all the radical sites
Modifies:
*/
//## operation getRadicalNode()
public LinkedHashSet getRadicalNode() {
//#[ operation getRadicalNode()
LinkedHashSet radicalNode = new LinkedHashSet();
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node n = (Node)iter.next();
Atom a = (Atom)n.getElement();
if (a.isRadical()) {
radicalNode.add(n);
}
}
return radicalNode;
//#]
}
/**
Requires:
Effects: calculate the total radical number in this chem graph.
Modifies:
*/
//## operation getRadicalNumber()
public int getRadicalNumber() {
//#[ operation getRadicalNumber()
int radicalNumber = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Object element = ((Node)(iter.next())).getElement();
radicalNumber += ((Atom)element).getRadicalNumber();
}
return radicalNumber;
//#]
}
//gmagoon 4/30/10: modified version of getRadicalNumber; same as getRadicalNumber, except it will not count 2S as radical
public int getUnpairedRadicalNumber() {
int radicalNumber = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Object element = ((Node)(iter.next())).getElement();
radicalNumber += ((Atom)element).getUnpairedRadicalNumber();
}
return radicalNumber;
}
public int getSiliconNumber() {
int siNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isSilicon()) {
siNum++;
}
}
return siNum;
}
public int getSulfurNumber() {
int sNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isSulfur()) {
sNum++;
}
}
return sNum;
}
public int getChlorineNumber() {
int ClNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isChlorine()) {
ClNum++;
}
}
return ClNum;
}
//## operation getSymmetryNumber()
public int getSymmetryNumber() {
//#[ operation getSymmetryNumber()
if (symmetryNumber < 0) calculateSymmetryNumber();
return symmetryNumber;
//#]
}
//## operation getThermoData()
public ThermoData getThermoData() {
//#[ operation getThermoData()
if (thermoData == null)
{
generateThermoData();
// thermoData is brand new gas phase estimate
if (Species.useSolvation) {
if (solvthermoData==null) generateSolvThermoData();
// solvthermoData is estimate of correction
thermoData.plus(solvthermoData);
thermoData.comments+=" corrected for solvation";
// thermoData is corrected
}
}
return thermoData;
//#]
}
public TransportData getTransportData() {
if (transportData == null) generateTransportData();
return transportData;
}
//## operation getThermoData()
public ThermoData getSolvationData() {
//#[ operation getThermoData()
if (solvthermoData == null) generateSolvThermoData();
return solvthermoData;
//#]
}
public AbramData getAbramData() {
//#[ operation getThermoData()
if (abramData == null) generateAbramData();
return abramData;
//#]
}
public UnifacData getUnifacData() {
//#[ operation getThermoData()
if (unifacData == null) generateUnifacData();
return unifacData;
//#]
}
/**
Added by: Amrit Jalan
Effects: calculate the raduis of the chemGraph using Abraham V values. (UNITS of radius = m)
*/
public double getRadius() {
double ri;
if (getCarbonNumber() == 0 && getOxygenNumber() == 0){ // Which means we ar dealing with HJ or H2
double ri3;
ri3 = 8.867 / 4.1887902; // 8.867 Ang^3 is the volume of a single Hydrogen Atom. 4.1887902 is 4pi/3
if (getHydrogenNumber() == 1){ // i.e. we are dealing with the Hydrogen radical
ri = Math.pow(ri3,0.333333) * 1.0e-10;
return ri;
}
if (getHydrogenNumber() == 2){ // i.e. we are dealing with the Hydrogen molecule
ri3 = 2*ri3; // Assumption: volume of H2 molecule ~ 2 * Volume of H atom
ri = Math.pow(ri3,0.333333) * 1.0e-10;
return ri;
}
}
double solute_V = getAbramData().V; //Units: cm3/100/mol
double volume = solute_V * 100 / 6.023e23; //Units: cm3/molecule
double ri3 = volume / 4.1887902 ; // Units: cm3 (4.1887902 is 4pi/3)
ri = Math.pow(ri3,0.333333)*0.01; //Returns the solute radius in 'm'
// double Ri=getUnifacData().R;
// ri=3.18*Math.pow(Ri,0.333333)*1.0e-10; // From Koojiman Ind. Eng. Chem. Res 2002, 41 3326-3328
return ri;
}
/**
Added by: Amrit Jalan
Effects: calculate the diffusivity of the chemGraph using radii, solvent viscosity and Stokes Einstein. (UNITS m2/sec)
*/
public double getDiffusivity() {
double speRad=getRadius();
Temperature sysTemp = ReactionModelGenerator.getTemp4BestKinetics();
//double solventViscosity = 9.65e-6 * Math.exp((811.75/sysTemp.getK()+(346920/sysTemp.getK()/sysTemp.getK()))); //Viscosity of octanol at a function of temperature. Obtained from Matsuo and Makita (INTERNATIONAL JOURNAL OF THERMOPHYSICSVolume 10, Number 4, 833-843, DOI: 10.1007/BF00514479)
//double solventViscosity = 0.136*Math.pow(10,-3); //Viscosity of liquid decane
//double solventViscosity = 0.546*Math.pow(10,-3); //Viscosity of liquid DMSO (dimethyl sulfoxide) Units: Pa.sec
//double solventViscosity = 0.6*Math.pow(10,-3); //Viscosity of liquid CH3CN Units: Pa.sec
//double solventViscosity = 1.122*Math.pow(10,-3); //Viscosity of liquid tetralin Source: International Journal of Thermophysics, Vol. 10, No. 4, 1989
//double solventViscosity = 0.404*Math.pow(10,-3); //Viscosity of water at 343 K
double solventViscosity = ReactionModelGenerator.getViscosity();
double denom = 132 * solventViscosity * speRad / 7;
double diffusivity = 1.381 * sysTemp.getK() * 1.0e-23 / denom; //sysTemp.getK()
return diffusivity;
}
/**
Requires:
Effects: find out the end of C=C=C... pattern
Modifies:
*/
//## operation getToEndOfAxis(Arc,Node,HashSet)
private static final Node getToEndOfAxis(Arc p_beginArc, Node p_beginNode, HashSet p_axis) {
//#[ operation getToEndOfAxis(Arc,Node,HashSet)
Arc nextArc = null;
Iterator iter = p_beginNode.getNeighbor();
while (iter.hasNext()) {
nextArc = (Arc)iter.next();
if (nextArc != p_beginArc) break;
}
p_axis.add(nextArc);
Node nextNode = nextArc.getOtherNode(p_beginNode);
FGElement fge = (FGElement)nextNode.getFgElement();
FGElement Cdd = FGElement.make("Cdd");
FGElement Sidd = FGElement.make("Sidd");
if (!fge.equals(Cdd) & !fge.equals(Sidd)) return nextNode;
else {
return getToEndOfAxis(nextArc,nextNode,p_axis);
}
//#]
}
//find the end of the Ct-Ct-Ct... pattern
//based on similar function getToEndOfAxis
private static final Node getToEndOfCumulatedTripleBondSystem(Arc p_beginArc, Node p_beginNode, HashSet p_axis) {
//#[ operation getToEndOfAxis(Arc,Node,HashSet)
Arc nextArc = null;
Iterator iter = p_beginNode.getNeighbor();
while (iter.hasNext()) {
nextArc = (Arc)iter.next();
if (nextArc != p_beginArc) break;
}
p_axis.add(nextArc);
Node nextNode = nextArc.getOtherNode(p_beginNode);
FGElement fge = (FGElement)nextNode.getFgElement();
FGElement Ct = FGElement.make("Ct");
if (!fge.equals(Ct)) return nextNode;
else {
return getToEndOfCumulatedTripleBondSystem(nextArc,nextNode,p_axis);
}
}
/**
Requires:
Effects: check if the element of every node is an atom, and if the element of every node is a bond.
Modifies:
*/
//## operation graphContentsOk(Graph)
public static boolean graphContentsOk(Graph p_graph) {
//#[ operation graphContentsOk(Graph)
Iterator iter = p_graph.getNodeList();
while (iter.hasNext()) {
Object atom = ((Node)iter.next()).getElement();
if (!(atom instanceof Atom)) return false;
}
iter = p_graph.getArcList();
while (iter.hasNext()) {
Object bond = ((Arc)iter.next()).getElement();
if (!(bond instanceof Bond)) return false;
}
return true;
//#]
}
/**
Requires:
Effects: return chemicalFormula's hashcode. i.e., all the isomers have the same hashcode
Modifies:
*/
//## operation hashCode()
public int hashCode() {
//#[ operation hashCode()
if (chemicalFormula == null) generateChemicalFormula();
return chemicalFormula.hashCode()+getTripleBonds()*300 + getSingleBonds()*1 + getDoubleBonds()*20;
//#]
}
/**
Requires:
Effects: check all the possible reacted sites in this chemgraph according to the pass-in functional group or functional group collection. If there are any matches, return all the matches in a linked list; otheriwse, return an empty list.
Modifies:
*/
//## operation identifyReactionMatchedSite(Matchable)
public LinkedHashSet identifyReactionMatchedSite(Matchable p_functionalGroup) {
//#[ operation identifyReactionMatchedSite(Matchable)
if (p_functionalGroup instanceof FunctionalGroup) {
FunctionalGroup fg = (FunctionalGroup)p_functionalGroup;
//boolean thisIsRadical = this.isRadical();
//boolean fgIsRadical = fg.isRadical();
//if (thisIsRadical == fgIsRadical) {
return getGraph().identifyAllOrderedMatchedSites(fg.getGraph());
//}
//else {
//return new LinkedHashSet();
//}
}
else if (p_functionalGroup instanceof FunctionalGroupCollection) {
LinkedHashSet result = new LinkedHashSet();
FunctionalGroupCollection fgc = (FunctionalGroupCollection)p_functionalGroup;
Iterator iter = fgc.getFunctionalGroups();
while (iter.hasNext()) {
FunctionalGroup fg = (FunctionalGroup)iter.next();
//boolean thisIsRadical = this.isRadical();
//boolean fgIsRadical = fg.isRadical();
//if (thisIsRadical == fgIsRadical) {
LinkedHashSet site = getGraph().identifyAllOrderedMatchedSites(fg.getGraph());
result.addAll(site);
//}
}
return result;
}
else {
throw new InvalidFunctionalGroupException();
}
//#]
}
/**
Requires:
Effects: get a collection of all the thermo matched site, this for corrections in GAPP.
Modifies:
*/
//## operation identifyThermoMatchedSite(FunctionalGroup)
public LinkedHashSet identifyThermoMatchedSite(FunctionalGroup p_functionalGroup) {
//#[ operation identifyThermoMatchedSite(FunctionalGroup)
return getGraph().identifyAllUnorderedMatchedSite(p_functionalGroup.getGraph());
//#]
}
/**
Requires:
Effects: return true if there is no cycle in the chem graph
Modifies:
*/
//## operation isAcyclic()
public boolean isAcyclic() {
//#[ operation isAcyclic()
return getGraph().isAcyclic();
//#]
}
/**
Requires:
Effects: return true iff this and p_chemGraph are equivalent chemgraphs.
Modifies:
*/
//## operation isEquivalent(ChemGraph)
public boolean isEquivalent(ChemGraph p_chemGraph) {
//#[ operation isEquivalent(ChemGraph)
if (chemicalFormula == null) generateChemicalFormula();
if (p_chemGraph.chemicalFormula == null) p_chemGraph.generateChemicalFormula();
if (!getChemicalFormula().equals(p_chemGraph.getChemicalFormula())) return false;
if (!getGraph().isEquivalent(p_chemGraph.getGraph())) return false;
return true;
//#]
}
/**
Requires:
Effects: return true iff this chemGraph contains forbidden structure.
Modifies:
*/
public static boolean isForbiddenStructure(Graph p_graph, int radNumber, int oNumber, int cNumber) {
/*Iterator iter = p_graph.getNodeList();
while (iter.hasNext()){
Node n = (Node)iter.next();
Atom atom = (Atom)n.getElement();
if (atom.isOxygen()) {
Iterator neighborarc = n.getNeighbor();
if (neighborarc.hasNext()){
Arc arc1 = (Arc)neighborarc.next();
if (neighborarc.hasNext()){
Node neighbornode1 = n.getOtherNode(arc1);
Arc arc2 = (Arc)neighborarc.next();
Node neighbornode2 = n.getOtherNode(arc2);
if (((Atom)neighbornode1.getElement()).isOxygen() && ((Atom)neighbornode2.getElement()).isOxygen())
return true;
}
}
}
}
return false;*/
for (Iterator iter = forbiddenStructure.iterator(); iter.hasNext(); ) {
FunctionalGroup fg = (FunctionalGroup)iter.next();
if (radNumber >= fg.rad_count && oNumber >= fg.O_count && cNumber >= fg.C_count) {
Graph g = fg.getGraph();
if (p_graph.isSub(g)) {
return true;
}
}
}
return false;
}
// Which forbidden structure forbade this chemgraph?
// returns the names of forbidden structures.
public static String whichForbiddenStructures(Graph p_graph, int radNumber, int oxygenNumber, int cycleNumber) {
String forbidden_by = "";
for (Iterator iter = forbiddenStructure.iterator(); iter.hasNext(); ) {
FunctionalGroup fg = (FunctionalGroup)iter.next();
Graph g = fg.getGraph();
if (p_graph.isSub(g)) {
forbidden_by += fg.getName() +", ";
}
}
if (forbidden_by=="") {
if (radNumber > MAX_RADICAL_NUM)
return "the maximum number of radicals per species (check the condition.txt file), ";
else if (oxygenNumber > MAX_OXYGEN_NUM)
return "the maximum number of oxygens per species (check the condition.txt file), ";
else if (cycleNumber > MAX_CYCLE_NUM)
return "the maximum number of cycles per species (check the condition.txt file), ";
else
return "no forbidden structures, ";
}
return forbidden_by;
}
/**
Requires:
Effects: return true iff this chemgraph contains radical site
Modifies:
*/
//## operation isRadical()
public boolean isRadical() {
//#[ operation isRadical()
return (getRadicalNumber() > 0);
//#]
}
/**
Requires:
Effects: if p_functionalGroup is a FunctionalGroup, return if this chemgraph is matched with it at the central nodes; if p_functionalGroup is a FunctionalGroupCollection, return if this chemgraph is matched with any of the functionalgroup in the collection at the central node. for all other case, return false.
Modifies:
*/
//## operation isSubAtCentralNodes(Matchable)
public boolean isSubAtCentralNodes(Matchable p_functional) {
//#[ operation isSubAtCentralNodes(Matchable)
if (this == p_functional) return false;
if (p_functional instanceof FunctionalGroup) {
return isSubAtCentralNodes((FunctionalGroup)p_functional);
}
else if (p_functional instanceof FunctionalGroupCollection) {
Iterator iter = ((FunctionalGroupCollection)p_functional).getFunctionalGroups();
while (iter.hasNext()) {
FunctionalGroup fg = (FunctionalGroup)iter.next();
if (isSubAtCentralNodes(fg)) return true;
}
return false;
}
else {
return false;
}
//#]
}
/**
Requires: both graph components belong to the same graph
Effects: return true if two graph components are equal
Modifies:
svp
*/
//## operation isSymmetric(GraphComponent, GraphComponent)
public boolean isSymmetric(GraphComponent p_gc1, GraphComponent p_gc2) {
//#[ operation isSymmetric(GraphComponent, GraphComponent)
Stack s1 = new Stack();
Stack s2 = new Stack();
if (p_gc1.isEquivalent(p_gc2, s1, s2)) {
resetStack(s1);
resetStack(s2);
getGraph().resetMatchedGC();
return true;
}
else {
resetStack(s1);
resetStack(s2);
getGraph().resetMatchedGC();
return false;
}
//#]
}
/**
Requires:
Effects: return if this chem graph is matched with p_functionalGroup at the central nodes.
Modifies:
*/
//## operation isSubAtCentralNodes(FunctionalGroup)
public boolean isSubAtCentralNodes(FunctionalGroup p_functionalGroup) {
//#[ operation isSubAtCentralNodes(FunctionalGroup)
return getGraph().isSubAtCentralNodes(p_functionalGroup.getGraph());
//#]
}
/**
Requires:
Effects: factory method for ChemGraph. make a new instance of ChemGraph. Do such things for it:
(1) add missing H
(2) generate chemical formula
(3) calculate symmetry number
(4) calculate thermal properties
Modifies:
*/
//## operation make(Graph)
/*public static ChemGraph make(Graph p_graph) throws InvalidChemGraphException, ForbiddenStructureException {
//#[ operation make(Graph)
double pT = System.currentTimeMillis();
Global.makeChemG++;
Species sp = SpeciesDictionary.getInstance().getSpeciesFromGraph(p_graph);
ChemGraph cg = null;
if (sp !=null){
if (sp.hasResonanceIsomers()){
Iterator rIter = sp.getResonanceIsomers();
while(rIter.hasNext()){
ChemGraph chemGraph = (ChemGraph)rIter.next();
if (chemGraph.graph.equals(p_graph)){
chemGraph.graph = p_graph;
return chemGraph;
}
}
}
else {
sp.chemGraph.graph = p_graph;
return sp.chemGraph;
}
}
if (cg == null){
try {
cg = new ChemGraph(p_graph);
cg.addMissingHydrogen();
if (cg.repOk()){
cg.generateChemicalFormula();
//cg.calculateSymmetryNumber();
Global.symmetryCG+=(System.currentTimeMillis()-pT)/1000/60;
pT = System.currentTimeMillis();
//cg.generateThermoData();
Global.thermoCG += (System.currentTimeMillis()-pT)/1000/60;
pT = System.currentTimeMillis();
//cg.calculateInternalRotor();
}
else {
throw new InvalidChemGraphException();
}
}
catch (ForbiddenStructureException e) {
throw new ForbiddenStructureException(e.getMessage());
}
}
Global.IRCG+=(System.currentTimeMillis()-pT)/1000/60;
return cg;
//#]
}*/
public static ChemGraph make(Graph p_graph, boolean hasHydrogen) throws InvalidChemGraphException, ForbiddenStructureException {
//#[ operation make(Graph)
double pT = System.currentTimeMillis();
ChemGraph cg = null;
if (cg == null){
cg = new ChemGraph(p_graph);
if (!hasHydrogen)
cg.addMissingHydrogen();
if (cg.repOk()){
cg.generateChemicalFormula();
}
else {
throw new InvalidChemGraphException();
}
//cgd.putSpecies(cg);
}
return cg;
//#]
}
public static ChemGraph make(Graph p_graph) throws InvalidChemGraphException, ForbiddenStructureException {
//#[ operation make(Graph)
double pT = System.currentTimeMillis();
//ChemGraphDictionary cgd = ChemGraphDictionary.getInstance();
ChemGraph cg = null;//= cgd.getChemGraphFromGraph(p_graph);
if (cg == null){
cg = new ChemGraph(p_graph);
cg.addMissingHydrogen();
if (cg.repOk()){
cg.generateChemicalFormula();
}
else {
Logger.error(getRepOkString());
throw new InvalidChemGraphException();
}
//cgd.putSpecies(cg);
}
return cg;
//#]
}
public static void addForbiddenStructure(FunctionalGroup fg) {
forbiddenStructure.add(fg);
}
/**
Requires:
Effects: read in forbidden structure for ChemGraph
Modifies: this.forbiddenStructure
*/
//## operation readForbiddenStructure()
public static void readForbiddenStructure() throws IOException {
//#[ operation readForbiddenStructure()
try {
String forbiddenStructureFile = System.getProperty("jing.chem.ChemGraph.forbiddenStructureFile");
if (forbiddenStructureFile == null) {
Logger.error("Undefined system property: jing.chem.ChemGraph.forbiddenStructureFile!");
Logger.error("No forbidden structure file defined!");
throw new IOException("Undefined system property: jing.chem.ChemGraph.forbiddenStructureFile");
//return;
}
FileReader in = new FileReader(forbiddenStructureFile);
BufferedReader data = new BufferedReader(in);
// step 1: read in structure
String line = ChemParser.readMeaningfulLine(data, true);
read: while (line != null) {
StringTokenizer token = new StringTokenizer(line);
String fgname = token.nextToken();
Graph fgGraph = null;
try {
fgGraph = ChemParser.readFGGraph(data);
}
catch (InvalidGraphFormatException e) {
throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage());
}
if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname);
//FunctionalGroup fg = FunctionalGroup.make(fgname, fgGraph);
FunctionalGroup fg = FunctionalGroup.makeForbiddenStructureFG(fgname, fgGraph);
forbiddenStructure.add(fg);
line = ChemParser.readMeaningfulLine(data, true);
}
in.close();
return;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new IOException(e.getMessage());
}
//#]
}
/**
Requires:
Effects: reset centralNode list in this ChemGraph according to node's CentralID information
Modifies: this.graph.centralNode
*/
//## operation refreshCentralNode()
public void refreshCentralNode() {
//#[ operation refreshCentralNode()
getGraph().refreshCentralNode();
//#]
}
/**
Requires:
Effects: check four aspects:
(1) if graph.repOk() defined in Graph class
(2) if graph is connected
(3) if the graph contents are atoms and bonds
(4) if the valency are okay for all atom
(5) if the radical number is in the limit
*/
//## operation repOk()
public boolean repOk() {
//#[ operation repOk()
// check if the graph is connected
if (!getGraph().repOk()){
setRepOkString("Something is wrong with the following chemgraph: " + this.toString());
return false;
}
// a chemical species should be a connected graph
if (!getGraph().isConnected()) {
setRepOkString("The following chemgraph is not a connected graph: " + this.toString());
return false;
}
// check if the elements stored in graph are atomd/bonds
if (!graphContentsOk(getGraph())) {
setRepOkString("The following chemgraph contains contents other than atoms or bonds: " + this.toString());
return false;
}
// check if the valency of every atom is satuated
//if (!valencyOk()) return false;
// check if the radical number greater than MAX_RADICAL_NUM
if (getRadicalNumber() > MAX_RADICAL_NUM) {
setRepOkString("The following chemgraph exceeds the maximum radicals allowed in a species: " + this.toString());
return false;
}
// check if the oxygen atom number is too large
if (getOxygenNumber() > MAX_OXYGEN_NUM) {
setRepOkString("The following chemgraph exceeds the maximum oxygens allowed (" + MAX_OXYGEN_NUM + ") in a species:\n" + this.toString());
return false;
}
if (getCarbonNumber() > MAX_CARBON_NUM) {
setRepOkString("The following chemgraph exceeds the maximum carbons allowed (" + MAX_CARBON_NUM + ") in a species:\n" + this.toString());
return false;
}
if (getSulfurNumber() > MAX_SULFUR_NUM) {
setRepOkString("The following chemgraph exceeds the maximum sulfurs allowed (" + MAX_SULFUR_NUM + ") in a species:\n" + this.toString());
return false;
}
if (getSiliconNumber() > MAX_SILICON_NUM) {
setRepOkString("The following chemgraph exceeds the maximum silicons allowed (" + MAX_SILICON_NUM + ") in a species:\n" + this.toString());
return false;
}
if (getHeavyAtomNumber() > MAX_HEAVYATOM_NUM) {
setRepOkString("The following chemgraph exceeds the maximum heavy atoms allowed (" + MAX_HEAVYATOM_NUM + ") in a species:\n" + this.toString());
return false;
}
return true;
//#]
}
/**
Requires:
Effects: reset reacting site as the pass-in p_site.
Modifies: this.graph.centralNode
*/
//## operation resetReactedSite(HashMap)
public void resetReactedSite(HashMap p_site) throws SiteNotInSpeciesException {
//#[ operation resetReactedSite(HashMap)
setCentralNode(p_site);
//#]
}
//## operation resetStack(Stack)
//svp
public void resetStack(Stack p_stack) {
//#[ operation resetStack(Stack)
while (!p_stack.empty()) {
GraphComponent gc = (GraphComponent)p_stack.pop();
gc.setMatchedGC(null);
}
return;
//#]
}
/**
Requires:
Effects: reset the only center to the p_node in this chem graph for thermo calculation
Modifies: this.graph.centralNode, and centralIDs in its associated nodes.
*/
//## operation resetThermoSite(Node)
public void resetThermoSite(Node p_node) {
//#[ operation resetThermoSite(Node)
getGraph().clearCentralNode();
getGraph().setCentralNode(1,p_node);
return;
//#]
}
/**
Requires:
Effects: reset centreNode list as the pass-in p_site.
Modifies: this.graph.centralNode
*/
//## operation setCentralNode(HashMap)
protected void setCentralNode(HashMap p_site) {
//#[ operation setCentralNode(HashMap)
try {
Graph g = getGraph();
g.clearCentralNode();
g.setCentralNodes(p_site);
}
catch (NotInGraphException e) {
throw new SiteNotInSpeciesException();
}
//#]
}
/**
Requires:
Effects: set GTPP as the thermoGAPP of this chem graph
Modifies: thermoGAPP
*/
//## operation setDefaultThermoGAPP()
public void setDefaultThermoGAPP() {
//#[ operation setDefaultThermoGAPP()
thermoGAPP = GATP.getINSTANCE();
return;
//#]
}
public void setDefaultTransportGAPP() {
transportGAPP = GATransportP.getINSTANCE();
return;
}
public void setDefaultSolvationGAPP() {
//#[ operation setDefaultThermoGAPP()
SolvationGAPP = GATP_Solvation.getINSTANCE();
return;
//#]
}
public void setDefaultAbramGAPP() {
//#[ operation setDefaultThermoGAPP()
abramGAPP = GATP_Abraham.getINSTANCE();
return;
//#]
}
public void setDefaultUnifacGAPP() {
//#[ operation setDefaultThermoGAPP()
unifacGAPP = GATP_Unifac.getINSTANCE();
return;
//#]
}
/**
Requires:
Effects: return a string of this chemgraph. the string includes two parts:
(1) chemical formula
(2) the string for the graph
Modifies:
*/
//## operation toString()
public String toString() {
//#[ operation toString()
String s = "ChemFormula: " + getChemicalFormula() + '\n';
s = s + getGraph().toStringWithoutCentralID();
return s;
//#]
}
public String toString(int i) {
//#[ operation toString()
String s ="";// "ChemFormula: " + getChemicalFormula() + '\n';
s = s + getGraph().toStringWithoutCentralID();
return s;
//#]
}
/**
Requires:
Effects: return a short string for this ChemGraph. it includes two parts:
(1) chemical formula
(2) the graph string without H
Modifies:
*/
//## operation toStringWithoutH()
public String toStringWithoutH() {
//#[ operation toStringWithoutH()
String s = "ChemFormula: " + getChemicalFormula() + '\n';
if (getHeavyAtomNumber() == 0)
s += getGraph().toStringWithoutCentralID();
else
s = s + getGraph().toStringWithoutCentralIDAndH();
return s;
//#]
}
/**
Requires:
Effects: return a short string for this ChemGraph. it includes two parts:
(1) the graph string without H
Modifies:
*/
//## operation toStringWithoutH()
public String toStringWithoutH(int i) {
//#[ operation toStringWithoutH()
String s = "";//= "ChemFormula: " + getChemicalFormula() + '\n';
if (getHeavyAtomNumber() == 0)
s += getGraph().toStringWithoutCentralID();
else
s = s + getGraph().toStringWithoutCentralIDAndH();
return s;
//#]
}
/**
Requires:
Effects: check all the atom to see if it satisfies:
Val of atom = radical number + ion number + sum of bond orders.
if it is satisfied, return true, otherwise return false.
Modifies:
*/
//## operation valencyOk()
public boolean valencyOk() throws InvalidNodeElementException {
//#[ operation valencyOk()
Iterator node_iter = graph.getNodeList();
while (node_iter.hasNext()) {
Node node = (Node)node_iter.next();
Atom atom = (Atom)node.getElement();
double val = atom.getValency();
Iterator arc_iter = node.getNeighbor();
while (arc_iter.hasNext()) {
Bond bond = (Bond)((Arc)(arc_iter.next())).getElement();
val -= bond.getOrder();
}
if (Math.abs(val) >= 1e-10) return false;
}
return true;
//#]
}
public int getMAX_OXYGEN_NUM() {
return MAX_OXYGEN_NUM;
}
public static int getMAX_RADICAL_NUM() {
return MAX_RADICAL_NUM;
}
public static HashSet getForbiddenStructure() {
return forbiddenStructure;
}
public int getInternalRotor() {
if (internalRotor <0 ){
calculateInternalRotor();
}
return internalRotor;
}
/*public HashSet getSymmetryAxis() {
return symmetryAxis;
}*/
protected String getUniqueString() {
return uniqueString;
}
public Graph getGraph() {
return graph;
}
public void setGraph(Graph p_graph){
graph = p_graph;
}
public Species getSpecies() {
return species;
}
public void setSpecies(Species p_Species) {
species = p_Species;
}
public GeneralGAPP getThermoGAPP() {
return thermoGAPP;
}
public GeneralAbramGAPP getAbramGAPP() {
return abramGAPP;
}
public void setThermoGAPP(GeneralGAPP p_GeneralGAPP) {
thermoGAPP = p_GeneralGAPP;
}
public void setAbramGAPP(GeneralAbramGAPP p_GeneralAbramGAPP) {
abramGAPP = p_GeneralAbramGAPP;
}
public static void setMaxCarbonNumber(int maxCNumber) {
MAX_CARBON_NUM = maxCNumber;
}
public static void setMaxOxygenNumber(int maxONumber) {
MAX_OXYGEN_NUM = maxONumber;
}
public static void setMaxRadicalNumber(int maxRadNumber) {
MAX_RADICAL_NUM = maxRadNumber;
}
public static void setMaxSulfurNumber(int maxSNumber) {
MAX_SULFUR_NUM = maxSNumber;
}
public static void setMaxSiliconNumber(int maxSiNumber) {
MAX_SILICON_NUM = maxSiNumber;
}
public static void setMaxHeavyAtomNumber(int maxHANumber) {
MAX_HEAVYATOM_NUM = maxHANumber;
}
public static void setMaxCycleNumber(int maxCycleNumber) {
MAX_CYCLE_NUM = maxCycleNumber;
}
public int getHeavyAtomNumber() {
return getCarbonNumber() + getOxygenNumber() + getSulfurNumber() + getSiliconNumber();
}
public void setRepOkString(String s) {
repOkString = s;
}
public static String getRepOkString() {
return repOkString;
}
public void appendThermoComments(String newComment) {
thermoComments += newComment + "\t";
}
public String getThermoComments() {
return thermoComments;
}
public void appendFreqComments(String newComment) {
freqComments += newComment + "\t";
}
public String getFreqComments() {
return freqComments;
}
}
/*********************************************************************
File Path : RMG\RMG\jing\chem\ChemGraph.java
*********************************************************************/
| source/RMG/jing/chem/ChemGraph.java | ////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2011 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.chem;
import java.io.*;
import java.util.*;
import jing.chemUtil.*;
import jing.chemParser.*;
import jing.chemUtil.Arc;
import jing.chemUtil.Node;
import jing.chemUtil.Graph;
import jing.param.Global;
import jing.param.Temperature;
import jing.rxnSys.Logger;
import jing.rxnSys.ReactionModelGenerator;
//## package jing::chem
//----------------------------------------------------------------------------
// jing\chem\ChemGraph.java
//----------------------------------------------------------------------------
//## class ChemGraph
public class ChemGraph implements Matchable {
protected static int MAX_OXYGEN_NUM = 10; //20 Modified by AJ //## attribute MAX_OXYGEN_NUM
protected static int MAX_CARBON_NUM = 30;//100 Modified by AJ //SS
protected static int MAX_CYCLE_NUM = 10; //SS (no fused rings); gmagoon: to turn fused rings off, set this to 1 (will exclude multiple non-fused rings, as well, I think)
/**
Maximal radical number allowed in a ChemGraph.
*/
protected static int MAX_RADICAL_NUM = 10; //## attribute MAX_RADICAL_NUM
protected static int MAX_SILICON_NUM = 10;
protected static int MAX_SULFUR_NUM = 10;
protected static int MAX_HEAVYATOM_NUM = 100;
protected static String repOkString = null;
public static boolean useQM = false;//gmagoon 6/15/09: flag for thermo estimation using quantum results; there may be a better place for this (Global?) but for now, this should work
public static boolean useQMonCyclicsOnly=false;
/**
Chemical Formula of a ChemGraph.
*/
protected String chemicalFormula = null; //## attribute chemicalFormula
/**
The overall forbidden structure. When any new ChemGraph instance is generated, RMG check if it has any of the forbidden structure. If it has, it wont be generated.
*/
protected static HashSet forbiddenStructure = new HashSet(); //## attribute forbiddenStructure
protected int internalRotor = -1; //## attribute internalRotor
/**
A collection of all the possible symmetry Axis in a ChemGraph.
For example: the C=C=O skeleton in (CH3)2C=C=O
*/
//protected HashSet symmetryAxis = null; //## attribute symmetryAxis
/**
Symmetry number of a ChemGraph. Used in calculating entropy.
*/
protected int symmetryNumber = -1; //## attribute symmetryNumber
/**
It is a unique string representation for this chem structure. The method to generating it has not implemented yet.
*/
protected String uniqueString; //## attribute uniqueString
protected Graph graph;
protected Species species;
protected ThermoData thermoData;
protected AbramData abramData;
protected UnifacData unifacData;
protected GeneralGAPP thermoGAPP;
protected GeneralSolvationGAPP SolvationGAPP;
protected GeneralAbramGAPP abramGAPP;
protected GeneralUnifacGAPP unifacGAPP;
protected ThermoData solvthermoData;
protected TransportData transportData;
protected GATransportP transportGAPP;
protected boolean fromprimarythermolibrary = false;
protected boolean isAromatic = false;
protected String InChI;
protected String InChIKey;
protected String thermoComments = "";
protected String freqComments = "";
// Constructors
private ChemGraph() {
}
private ChemGraph(Graph p_graph) throws ForbiddenStructureException {
graph = p_graph;
// isAromatic = isAromatic();
if (isForbiddenStructure(p_graph,getRadicalNumber(),getOxygenNumber(),getCarbonNumber()) || getRadicalNumber() > MAX_RADICAL_NUM || getOxygenNumber() > MAX_OXYGEN_NUM || getCycleNumber() > MAX_CYCLE_NUM) {
//if (getRadicalNumber() > MAX_RADICAL_NUM || getOxygenNumber() > MAX_OXYGEN_NUM || getCycleNumber() > MAX_CYCLE_NUM) {
String message = "The molecular structure\n"+ p_graph.toString() + " is forbidden by "+whichForbiddenStructures(p_graph, getRadicalNumber(), getOxygenNumber(), getCycleNumber()) +"and not allowed.";
ThermoData themo_from_library = GATP.getINSTANCE().primaryLibrary.getThermoData(getGraph());
if ( themo_from_library != null) {
Logger.warning(message);
Logger.warning(String.format("But it's in the %s, so it will be allowed anyway.\n",themo_from_library.getSource() ));
// nb. the source String begins "Primary Thermo Library:"
}
else{
graph = null;
throw new ForbiddenStructureException(message);
}
}
this.determineAromaticityAndWriteBBonds();
}
public void determineAromaticityAndWriteBBonds() {
// If there are no cycles, cannot be aromatic
if (graph.getCycleNumber() == 0) return;
// Check each cycle for aromaticity
for (Iterator cyclesIter = graph.getCycle().iterator(); cyclesIter.hasNext();) {
int piElectronsInCycle = 0;
LinkedList graphComps = (LinkedList)cyclesIter.next();
boolean[] hadPiElectrons = new boolean[graphComps.size()];
boolean cycleStartedWithNode = false;
for (int numComps=0; numComps<graphComps.size(); numComps++) {
GraphComponent gc = (GraphComponent)graphComps.get(numComps);
if (gc instanceof Node) {
if (numComps==0) cycleStartedWithNode = true;
Atom a = (Atom)((Node)gc).getElement();
if (a.isBiradical()) {
piElectronsInCycle += 2;
hadPiElectrons[numComps] = true;
}
else if (!a.isRadical()) {
Iterator neighbors = ((Node)gc).getNeighbor();
int usedValency = 0;
/*
* We count here the number of double bonds attached to a particular
* atom.
*
* We do this because we don't want that species with a
* Cdd type carbon atom, i.e. carbon bonded by two double bonds,
* is identified as being aromatic.
*
* Previously, a five-membered cyclic species, containing
* three double bonds with one Cdd carbon, would be perceived
* as aromatic since 3*2 = 6 "Pi" electrons were counted,
* and a cyclic structure was present.
*
* This patch, albeit not very general, counts the total
* number of double bonds for a particular atom. If a second
* double bond is detected, the pi-electron counter is not updated
* by adding two.
*
* This makes at least some chemical sence, as you could
* argue that the second pair electrons in the pi-bonds (perpendicular to the other
* pair of electrons) does not interact and conjugate with the
* pi electrons of other electrons.
*
*/
int number_of_double_bonds = 0;
while (neighbors.hasNext()) {
Arc nodeA= (Arc)neighbors.next();
double order = ((Bond)(nodeA.getElement())).getOrder();
if(order==2) number_of_double_bonds++;
if(number_of_double_bonds != 2)
usedValency += ((Bond)(nodeA.getElement())).getOrder();
}
if (a.getChemElement().getValency()-usedValency >= 2) {
piElectronsInCycle += 2;
hadPiElectrons[numComps] = true;
}
}
} else if (gc instanceof Arc) {
Bond b = (Bond)((Arc)gc).getElement();
/*
* For now, species with a triple bond conjugated to two double bonds
* would also contribute to the pi electron count. Hence, molecules
* such as benzyne (InChI=1S/C6H4/c1-2-4-6-5-3-1/h1-4H) would
* have a hueckel number of 6 and would then be perceived as aromatic.
*
* The atomtype of the triple bonded carbons (Ct) would be changed
* to Cb and hence an atom would be added afterwards, in a place
* where that would not possible.
*
* In order to avoid this problem, an if conditional is added that
* checks whether the iterated bond is a double bond. If not,
* contributions to the pi electron count are not taken into account.
*/
if(b.getOrder() == 2){
int bondPiElectrons = b.getPiElectrons();
if (bondPiElectrons > 0) {
piElectronsInCycle += bondPiElectrons;
hadPiElectrons[numComps] = true;
}
}
}
}
// Check if the # of piElectronsInCycle = 4*n+2 (Huckel's rule)
int huckelMagicNumber = 2;
boolean obeysHuckelRule = false;
while (piElectronsInCycle >= huckelMagicNumber) {
if (piElectronsInCycle == huckelMagicNumber) {
obeysHuckelRule = true;
break;
}
else huckelMagicNumber += 4;
}
if (!obeysHuckelRule) return;
// Check if each node (atom) contributed to pi electrons in cycle
for (int i=0; i<hadPiElectrons.length/2; i++) {
if (cycleStartedWithNode) {
if (!hadPiElectrons[2*i]) {
if (i==0) {
if (!hadPiElectrons[1] && !hadPiElectrons[hadPiElectrons.length-1]) return;
} else {
if (!hadPiElectrons[2*i-1] && !hadPiElectrons[2*i+1]) return;
}
}
}
else {
if (!hadPiElectrons[2*i+1]) {
if (i==hadPiElectrons.length-1) {
if (!hadPiElectrons[0] && !hadPiElectrons[hadPiElectrons.length-2]) return;
} else {
if (!hadPiElectrons[2*i] && !hadPiElectrons[2*i+2]) return;
}
}
}
}
// If we've reached here, our assumption is that the cycle is aromatic
isAromatic = true;
for (int numComps=0; numComps<graphComps.size(); numComps++) {
GraphComponent gc = (GraphComponent)graphComps.get(numComps);
if (gc instanceof Arc) {
Arc currentArc = (Arc)gc;
Bond currentBond = (Bond)currentArc.getElement();
currentArc.setElement(currentBond.changeBondToAromatic());
}
}
/**
* After the bonds that were previously defined as "S" or "D" bonds,
* have been renamed to "B" bonds,
* We have to re-perceive the atom type of the atoms in the adjacency list.
* This is done by re-iterating over all nodes and calling the
* Node.updateFgElement.
*
* If this is not done, the thermodynamic properties estimation
* will fail to assign Cb GAVs to those atoms perceived as aromatic.
*
*/
for (int numComps=0; numComps<graphComps.size(); numComps++) {
GraphComponent gc = (GraphComponent)graphComps.get(numComps);
if (gc instanceof Node) {
Node currentNode = (Node)gc;
currentNode.updateFgElement();//update the FgElement
}
}
}
}
/*private boolean isAromatic() {
//first see if it is cyclic
if (graph.getCycleNumber() == 0)
return false;
//if cyclic then iterate over all the cycles
Iterator cyclesIter = graph.getCycle();
while (cyclesIter.hasNext()){
LinkedList cycle = (LinkedList)cyclesIter.next();
boolean hasdoublebond = false;
boolean quarternaryAtom = false;
boolean monoRadical = false;
int unsaturatedCarbon =0 ;
for (int i=0; i<=cycle.size(); i++){
GraphComponent gc = (GraphComponent)cycle.get(i);
if (gc instanceof Arc){
if ( ((Bond)((Arc)gc).getElement()).isDouble())
hasdoublebond = true;
}
else {
Atom a = (Atom)((Node)gc).getElement();
// is it unsaturate Carbon
if (a.isCarbon() && !a.isRadical())
unsaturatedCarbon++;
//it is a monoradical
if (a.freeElectron.order == 1){
monoRadical = true;
return false;
}
//you have to check for SO2RR radical presence
///what is a quarternary atom...i will check
}
}
if (!hasdoublebond || unsaturatedCarbon > 1)
return false;
//first check if the ring has exocyclic pi bonds
for (int i=0; i<=cycle.size();i++){
GraphComponent gc = (GraphComponent)cycle.get(i);
if (gc instanceof Node){
Iterator neighbors = gc.getNeighbor();
while (neighbors.hasNext()){
Arc neighborArc = (Arc)neighbors.next();
}
}
}
}
}*/
/**
Requires:
Effects: saturate all the node atom's undefined valence by adding Hydrogen.
Modifies: this.graph.nodeList
*/
//## operation addMissingHydrogen()
public void addMissingHydrogen() {
//#[ operation addMissingHydrogen()
Atom H = Atom.make(ChemElement.make("H"), FreeElectron.make("0"));
Bond S = Bond.make("S");
LinkedHashMap addedH = new LinkedHashMap();
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
int val = (int)atom.getValency();
double bondOrder = 0;
Iterator neighbor_iter = node.getNeighbor();
while (neighbor_iter.hasNext()) {
Arc arc = (Arc)neighbor_iter.next();
Bond bond = (Bond)arc.getElement();
bondOrder += bond.getOrder();
}
// if (bondOrder > val) throw new InvalidConnectivityException();
// else if (bondOrder < val) {
// addedH.put(node, new Integer(val-bondOrder));
// }
if (bondOrder < val) {
addedH.put(node, new Integer(val-(int)(bondOrder+1.0e-8)));
}
}
Graph g = getGraph();
iter = addedH.keySet().iterator();
while (iter.hasNext()) {
Node node = (Node)iter.next();
int Hnum = ((Integer)addedH.get(node)).intValue();
for (int i=0;i<Hnum; i++) {
Node newNode = g.addNode(H);
g.addArcBetween(node, S, newNode);
}
node.updateFgElement();
}
return;
//#]
}
public static ChemGraph saturate(ChemGraph p_chemGraph) {
//#[ operation saturate(ChemGraph)
int max_radNum_molecule = ChemGraph.getMAX_RADICAL_NUM();
int max_radNum_atom = Math.min(8,max_radNum_molecule);
ChemGraph result = null;
try {
result = ChemGraph.copy(p_chemGraph);
}
catch (Exception e) {
Logger.logStackTrace(e);
Logger.critical(e.getMessage());
System.exit(0);
}
FreeElectron satuated = FreeElectron.make("0");
Atom H = Atom.make(ChemElement.make("H"),satuated);
Bond S = Bond.make("S");
Graph g = result.getGraph();
int nn = g.getHighestNodeID();
for (int i = 0 ; i < nn; i++) {
Node node = g.getNodeAt(i);
if (node != null) {
Atom atom = (Atom)node.getElement();
int HNum = atom.getRadicalNumber();
if (atom.isRadical()) {
Atom newAtom = new Atom(atom.getChemElement(),satuated);
node.setElement(newAtom);
node.updateFeElement();
for (int j = 0; j < HNum; j++) {
Node n = g.addNode(H);
g.addArcBetween(node,S,n);
}
node.updateFgElement();
}
}
}
return result;
/*
int max_radNum_molecule = ChemGraph.getMAX_RADICAL_NUM();
int max_radNum_atom = Math.min(8,max_radNum_molecule);
int [] idArray = new int[max_radNum_molecule];
Atom [] atomArray = new Atom[max_radNum_molecule];
Node [][] newnode = new Node[max_radNum_molecule][max_radNum_atom];
int radicalSite = 0;
Iterator iter = p_chemGraph.getNodeList();
FreeElectron satuated = FreeElectron.make("0");
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isRadical()) {
radicalSite ++;
// save the old radical atom
idArray[radicalSite-1] = node.getID().intValue();
atomArray[radicalSite-1] = atom;
// new a satuated atom and replace the old one
Atom newAtom = new Atom(atom.getChemElement(),satuated);
node.setElement(newAtom);
node.updateFeElement();
}
}
// add H to satuate chem graph
Atom H = Atom.make(ChemElement.make("H"),satuated);
Bond S = Bond.make("S");
for (int i=0;i<radicalSite;i++) {
Node node = p_chemGraph.getNodeAt(idArray[i]);
Atom atom = atomArray[i];
int HNum = atom.getRadicalNumber();
for (int j=0;j<HNum;j++) {
newnode[i][j] = g.addNode(H);
g.addArcBetween(node,S,newnode[i][j]);
}
node.updateFgElement();
}
*/
//#]
}
/**
Requires: acyclic ChemGraph
Effects: calculate and return the symmetry number centered at p_node atom
Modifies:
*/
//## operation calculateAtomSymmetryNumber(Node)
public int calculateAtomSymmetryNumber(Node p_node) {
//#[ operation calculateAtomSymmetryNumber(Node)
// note: acyclic structure!!!!!!!!!!!!!
int sn = 1;
// if no neighbor or only one neighbor, sigma = 1, return 1;
int neighborNumber = p_node.getNeighborNumber();
if (neighborNumber < 2) return sn;
Atom atom = (Atom)p_node.getElement();
Iterator neighbor_iter = p_node.getNeighbor();
FGElement fge = (FGElement)p_node.getFgElement();
if (!atom.isRadical()) {
// satuated atom symmetric number calculation
if (fge.equals(FGElement.make("Cs")) || fge.equals(FGElement.make("Sis"))) {
// Cs:
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
Arc a3 = (Arc)neighbor_iter.next();
Arc a4 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
if (p_node.isSymmetric(a1,a3)) {
if (p_node.isSymmetric(a1,a4)) {
// AAAA
sn *= 12;
}
else {
// AAAB
sn *= 3;
}
}
else {
if (p_node.isSymmetric(a1,a4)) {
// AAAB
sn *= 3;
}
else if (p_node.isSymmetric(a3,a4)) {
// AABB
sn *= 2;
}
else {
// AABC
}
}
}
else {
if (p_node.isSymmetric(a1,a3)) {
if (p_node.isSymmetric(a1,a4)) {
// AAAB
sn *= 3;
}
else if (p_node.isSymmetric(a2,a4)) {
// AABB
sn *= 2;
}
else {
// AABC
}
}
else if (p_node.isSymmetric(a2,a3)) {
if (p_node.isSymmetric(a1,a4)) {
// AABB
sn *= 2;
}
else if (p_node.isSymmetric(a2,a4)) {
// AAAB
sn *= 3;
}
else {
// AABC
}
}
else {
// AABC or ABCD
}
}
}
else if (fge.equals(FGElement.make("Os")) || fge.equals(FGElement.make("Ss"))) {
// Os:
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
sn *= 2;
}
}
else if (fge.equals(FGElement.make("Cdd")) || fge.equals(FGElement.make("Sidd"))) {
// Cdd:
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
sn *= 2;
}
}
}
else {
// radical symmetric number calculation
if (fge.equals(FGElement.make("Cs")) || fge.equals(FGElement.make("Sis"))) {
// only consider Cs. and Cs..
FreeElectron fe = atom.getFreeElectron();
if (fe.getOrder() == 1) {
// mono-radical Cs.
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
Arc a3 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
if (p_node.isSymmetric(a1,a3))
sn *= 6;
else
sn *= 2;
}
else {
if (p_node.isSymmetric(a1,a3) || p_node.isSymmetric(a2,a3))
sn *= 2;
}
}
else if (fe.getOrder() == 2) {
// bi-radical Cs..
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2))
sn *= 2;
}
}
}
return sn;
//#]
}
//takes the fragments and corresponding rotor nodes for each side of the rotor
public int calculateRotorSymmetryNumber(Node p_node1, Node p_node2) {
//first calculate the symmetry number for each fragment
int frag1sn=calculateRotorFragmentSymmetryNumber(p_node1);//will return 1, 2, or 3
int frag2sn=calculateRotorFragmentSymmetryNumber(p_node2);//will return 1, 2, or 3
if(frag1sn==3 || frag2sn==3){
if(frag1sn==3){
if(frag2sn==3) return 3; //example: ethane
else if (frag2sn==2) return 6; //example: toluene
else return 3; //frag2sn==1; example: methanol
}
else{//frag2sn==3 (and frag1sn!=3)
if (frag2sn==2) return 6;//see above
else return 3; //frag1sn==1; see above
}
}
else if(frag1sn==2 || frag2sn==2){
return 2; //see "full" code below
//if(frag1sn==2){
//if(frag2sn==2) return 2; //example: biphenyl
//else return 2; //frag2sn==1; example: phenol
//}
//else{//frag2sn==2 (and frag1sn=1)
//return 2;//see above
//}
}
//otherwise, both frag1sn and frag2sn equal 1
return 1;
}
//returns 1, 2, or 3 based on the rotor fragment and rotor node passed in
//code is based off of calculateAtomSymmetryNumber as the idea is similar, but we must be able to handle incomplete fragments, triple bonds, and aromatic structures
//code does not handle radicals at present
public int calculateRotorFragmentSymmetryNumber(Node p_node) {
Atom atom = (Atom)p_node.getElement();
Iterator neighbor_iter = p_node.getNeighbor();
FGElement fge = (FGElement)p_node.getFgElement();
if(atom.isRadical()){
Logger.critical("calculateRotorFragmentSymmetryNumber() does not support radical sites");
System.exit(0);
}
// if no neighbor or only one neighbor, sigma = 1, return 1;
int neighborNumber = p_node.getNeighborNumber();
if (neighborNumber < 2){
if(fge.equals(FGElement.make("Ct"))){//triple bond case
//find the end of the cumulated triple bond system
Node n1 = p_node;
LinkedHashSet axis = new LinkedHashSet();
Arc arc = (Arc)neighbor_iter.next();
axis.add(arc);
p_node = getToEndOfCumulatedTripleBondSystem(arc,p_node,axis);
//use the new, non-Ct node for subsequent calculations
fge = (FGElement)p_node.getFgElement();
neighbor_iter = p_node.getNeighbor();
fge = (FGElement)p_node.getFgElement();
}
else{//e.g. peroxides, alcohols, etc.
return 1;
}
}
if (fge.equals(FGElement.make("Cs")) || fge.equals(FGElement.make("Sis"))) {
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
Arc a3 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
if (p_node.isSymmetric(a1,a3))
return 3;//AAA*//e.g. methyl rotor
}
}
else if(fge.equals(FGElement.make("Cb")) || fge.equals(FGElement.make("Cbf"))){
Arc a1 = (Arc)neighbor_iter.next();
Arc a2 = (Arc)neighbor_iter.next();
if (p_node.isSymmetric(a1,a2)) {
return 2;//AA*//e.g. phenyl group
}
}
return 1;
}
/**
Requires: acyclic ChemGraph
Effects: calculate and return the symmetry number by all the possible symmetry axis in this ChemGraph.
Modifies:
*/
//## operation calculateAxisSymmetryNumber()
public int calculateAxisSymmetryNumber() {
//#[ operation calculateAxisSymmetryNumber()
int sn = 1;
// note: acyclic structure!!!!!!!!!!!!!
LinkedHashSet symmetryAxis = new LinkedHashSet();
Iterator iter = getArcList();
while (iter.hasNext()) {
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (bond.isDouble()&&!arc.getInCycle()) {//2/22/10 gmagoon: added check to make sure the arc is not in a cycle; hopefully this should prevent infinite recursion errors in getToEndOfAxis caused by cyclic species like cyclic, cumulenic C3 while still preserving the ability to estimate axis symmetry number for "cyclic" cases where the axis is not part of the cycle
Iterator neighbor_iter = arc.getNeighbor();
Node n1 = (Node)neighbor_iter.next();
Node n2 = (Node)neighbor_iter.next();
// FGElement Cd = FGElement.make("Cd");
FGElement Cdd = FGElement.make("Cdd");
// FGElement Sid = FGElement.make("Sid");
FGElement Sidd = FGElement.make("Sidd");
FGElement fge1 = (FGElement)n1.getFgElement();
FGElement fge2 = (FGElement)n2.getFgElement();
LinkedHashSet axis = new LinkedHashSet();
axis.add(arc);
if (fge1.equals(Cdd) || fge1.equals(Sidd)) n1 = getToEndOfAxis(arc,n1,axis);
if (fge2.equals(Cdd) || fge2.equals(Sidd)) n2 = getToEndOfAxis(arc,n2,axis);
Atom atom1 = (Atom)n1.getElement();
Atom atom2 = (Atom)n2.getElement();
if (atom1.isRadical() || atom2.isRadical()) return sn;
Bond D = Bond.make("D");
if (!symmetryAxis.contains(axis)) {
symmetryAxis.add(axis);
boolean l1 = n1.isLeaf();
boolean l2 = n2.isLeaf();
if (!l1 && !l2) {
Iterator i1 = n1.getNeighbor();
Iterator i2 = n2.getNeighbor();
Arc a1 = (Arc)i1.next();
if (((Bond)a1.getElement()).equals(D)) a1 = (Arc)i1.next();
Arc a2 = (Arc)i1.next();
if (((Bond)a2.getElement()).equals(D)) a2 = (Arc)i1.next();
Arc a3 = (Arc)i2.next();
if (((Bond)a3.getElement()).equals(D)) a3 = (Arc)i2.next();
Arc a4 = (Arc)i2.next();
if (((Bond)a4.getElement()).equals(D)) a4 = (Arc)i2.next();
if (n1.isSymmetric(a1,a2) && n2.isSymmetric(a3,a4)) {
sn *= 2;
}
}
else if (!l1 && l2) {
Iterator i = n1.getNeighbor();
Arc a1 = (Arc)i.next();
if (((Bond)a1.getElement()).equals(D)) a1 = (Arc)i.next();
Arc a2 = (Arc)i.next();
if (((Bond)a2.getElement()).equals(D)) a2 = (Arc)i.next();
if (n1.isSymmetric(a1,a2)) {
sn *= 2;
}
}
else if (l1 && !l2) {
Iterator i = n2.getNeighbor();
Arc a1 = (Arc)i.next();
if (((Bond)a1.getElement()).equals(D)) a1 = (Arc)i.next();
Arc a2 = (Arc)i.next();
if (((Bond)a2.getElement()).equals(D)) a2 = (Arc)i.next();
if (n2.isSymmetric(a1,a2)) {
sn *= 2;
}
}
}
}
}
return sn;
//#]
}
/**
Requires: acyclic ChemGraph
Effects: calculate and return the symmetry number centered at p_arc bond
Modifies:
*/
//## operation calculateBondSymmetryNumber(Arc)
public int calculateBondSymmetryNumber(Arc p_arc) {
//#[ operation calculateBondSymmetryNumber(Arc)
// note: acyclic structure!!!!!!!!!!!!!
int sn = 1;
// if no neighbor or only one neighbor, sigma = 1, return 1;
int neighborNumber = p_arc.getNeighborNumber();
if (neighborNumber != 2) throw new InvalidNeighborException("bond has " + neighborNumber + " neighbor!");
Bond bond = (Bond)p_arc.getElement();
Iterator neighbor_iter = p_arc.getNeighbor();
Node n1 = (Node)neighbor_iter.next();
Node n2 = (Node)neighbor_iter.next();
if (bond.isSingle() || bond.isDouble() || bond.isTriple()) {
if (p_arc.isSymmetric(n1,n2)) {
boolean opt = checkOpticalIsomer(p_arc);
if (!opt) sn *= 2;
}
}
return sn;
//#]
}
/**
Requires:
Effects: return Cp(T)
Modifies:
*/
//## operation calculateCp(Temperature)
public double calculateCp(Temperature p_temperature) {
//#[ operation calculateCp(Temperature)
return getThermoData().calculateCp(p_temperature);
//#]
}
/**
Requires:
Effects: calculate and return the symmetry number of the cyclic portion of this ChemGraph
Modifies:
svp
*/
//## operation calculateCyclicSymmetryNumber()
public int calculateCyclicSymmetryNumber(){
//#[ operation calculateCyclicSymmetryNumber()
int sn = 1;
LinkedList ring_structures = new LinkedList();//list of ring structures
LinkedList cycle_list = new LinkedList();//list of cycles
Iterator cycle_iter = getGraph().getCycle().iterator();
while (cycle_iter.hasNext()){
LinkedList current_cycle = (LinkedList)cycle_iter.next();
cycle_list.add(current_cycle);
}
//if 2 graph components share at least one cycle, they belong to the same ring structure
for (int i = 0; i <= cycle_list.size()-1; i++){
LinkedList current_ring = (LinkedList)cycle_list.get(i);
if (ring_structures.isEmpty()){
ring_structures.add(current_ring);
}
else{
int same_gc = 0;
Iterator ring_structure_iter = ring_structures.iterator();
Iterator current_ring_iter = current_ring.iterator();
while (ring_structure_iter.hasNext()){
LinkedList ring_structure = (LinkedList) ring_structure_iter.next();
while (current_ring_iter.hasNext()) {
GraphComponent gc = (GraphComponent) current_ring_iter.next();
if (ring_structure.contains(gc)) {
Iterator current_iter = current_ring.iterator();
while (current_iter.hasNext()){
GraphComponent current_gc = (GraphComponent)current_iter.next();
if (!ring_structure.contains(current_gc)){
ring_structure.add(current_gc);
ring_structures.set(ring_structures.indexOf(ring_structure), ring_structure);
}
}
same_gc++;
}
}
}
if (same_gc == 0){
ring_structures.add(current_ring);
}
}
if (i != cycle_list.size()-1){
for (int j = 1; j <= cycle_list.size()-1; j++){
LinkedList next_cycle = (LinkedList)cycle_list.get(j);
Iterator ring_structures_iter = ring_structures.iterator();
Iterator next_cycle_iter = next_cycle.iterator();
while (ring_structures_iter.hasNext()){
LinkedList current_ring_structure = (LinkedList)ring_structures_iter.next();
while (next_cycle_iter.hasNext()){
GraphComponent gc = (GraphComponent)next_cycle_iter.next();
if (current_ring_structure.contains(gc)){
Iterator ring_iter = next_cycle.iterator();
while(ring_iter.hasNext()){
GraphComponent current_gc = (GraphComponent)ring_iter.next();
if (!current_ring_structure.contains(current_gc)){
current_ring_structure.add(current_gc);
ring_structures.set(ring_structures.indexOf(current_ring_structure),current_ring_structure);
}
}
break;
}
}
}
}
}
}
Iterator iter = ring_structures.iterator();
while (iter.hasNext()){
LinkedList current_ring_structure = (LinkedList)iter.next();
Iterator gc_iter = current_ring_structure.iterator();
LinkedList node_list = new LinkedList(); //list of all cyclic nodes
LinkedList arc_list = new LinkedList(); //list of all cyclic arcs
while (gc_iter.hasNext()){
GraphComponent gc = (GraphComponent)gc_iter.next();
gc.setVisited(false);
if (gc instanceof Node){
node_list.add(gc);
}
else {
arc_list.add(gc);
}
}
//find all sets of equal nodes
LinkedList equal_node_list = new LinkedList();
for (int i = 0; i <= node_list.size() - 2; i++) {
Node current = (Node) node_list.get(i);
if (!current.isVisited()) {
LinkedList equal_list = new LinkedList(); //list of equivalent nodes
current.setVisited(true);
equal_list.add(current);
for (int j = i + 1; j <= node_list.size() - 1; j++) {
Node next = (Node) node_list.get(j);
Iterator list_iter = equal_list.iterator();
while (list_iter.hasNext()) {
current = (Node) list_iter.next();
if (isSymmetric(current, next)) {
equal_list.add(next);
next.setVisited(true);
break;
}
}
}
equal_node_list.add(equal_list); //add list of equivalent nodes to list of sets of equivalent nodes
}
}
//find all sets of equal arcs
LinkedList equal_arc_list = new LinkedList();
for (int i = 0; i <= arc_list.size() - 2; i++) {
Arc current = (Arc) arc_list.get(i);
if (!current.isVisited()) {
LinkedList equal_list = new LinkedList(); //list of equivalent arcs
current.setVisited(true);
equal_list.add(current);
for (int j = i + 1; j <= arc_list.size() - 1; j++) {
Arc next = (Arc) arc_list.get(j);
Iterator list_iter = equal_list.iterator();
while (list_iter.hasNext()) {
current = (Arc) list_iter.next();
if (isSymmetric(current, next)) {
equal_list.add(next);
next.setVisited(true);
break;
}
}
}
equal_arc_list.add(equal_list); //add list of equivalent arcs to list of sets of equivalent arcs
}
}
//find largest set of equal nodes
int node_sn = 1;
Iterator node_list_iter = equal_node_list.iterator();
while (node_list_iter.hasNext()) {
LinkedList current = (LinkedList) node_list_iter.next();
if (current.size() > node_sn) {
node_sn = current.size(); //node symmetry number = size of largest set of equivalent nodes
}
}
//find largest set of equal arcs
int arc_sn = 1;
Iterator arc_list_iter = equal_arc_list.iterator();
while (arc_list_iter.hasNext()) {
LinkedList current = (LinkedList) arc_list_iter.next();
if (current.size() > arc_sn) {
arc_sn = current.size(); //arc symmetry number = size of largest set of equivalent arcs
}
}
if (node_sn == node_list.size() && arc_sn == arc_list.size()) { //all nodes equal and all arcs equal
sn *= node_sn;
sn *= 2;
Node first_node = (Node)node_list.getFirst();
FGElement fge = (FGElement)first_node.getFgElement();
if (fge.equals(FGElement.make("Cs"))){
LinkedList acyclic_neighbor = new LinkedList();
Iterator neighbor_iter = first_node.getNeighbor();
while (neighbor_iter.hasNext()){
Arc arc = (Arc)neighbor_iter.next();
if (!arc.getInCycle()){
acyclic_neighbor.add(arc);
}
}
if (acyclic_neighbor.size() == 2){
Arc a1 = (Arc) acyclic_neighbor.getFirst();
Arc a2 = (Arc) acyclic_neighbor.getLast();
if (!first_node.isSymmetric(a1, a2)) {
sn /= 2;
}
}
}
}
else {
if (node_sn >= arc_sn) {
sn *= node_sn;
}
else {
sn *= arc_sn;
}
}
//if (sn >= 2 && sn%2 == 0){//added by Sally for non-planar PAH's
//sn = correctSymmetryNumber(sn);
//}
}
graph.setCycle(null);
graph.formSSSR();
return sn;
//#]
}
/**
Requires:
Effects: return G(T)
Modifies:
*/
//## operation calculateG(Temperature)
public double calculateG(Temperature p_temperature) {
//#[ operation calculateG(Temperature)
return getThermoData().calculateG(p_temperature);
//#]
}
/**
Requires:
Effects:return H(T)
Modifies:
*/
//## operation calculateH(Temperature)
public double calculateH(Temperature p_temperature) {
//#[ operation calculateH(Temperature)
return getThermoData().calculateH(p_temperature);
//#]
}
//## operation calculateInternalRotor()
public void calculateInternalRotor() {
//#[ operation calculateInternalRotor()
// add more check for resonance axis!!
int rotor = 0;
Graph g = getGraph();
for (Iterator iter = g.getArcList(); iter.hasNext();) {
Arc a = (Arc)iter.next();
Bond bond = (Bond)a.getElement();
if (bond.isSingle() && !a.getInCycle()) {
Iterator atomIter = a.getNeighbor();
Node n1 = (Node)atomIter.next();
Node n2 = (Node)atomIter.next();
if (!n1.isLeaf() && !n2.isLeaf()) {
rotor++;
}
}
}
internalRotor = rotor;
//#]
}
//uses same algorithm as calculate internal rotor, but stores the two atoms involved in the rotor and all the atoms on one side of the rotor (specifically, the side corresponding to the 2nd atom of the rotor)
//the information is returned in a LinkedHashMap where the Key is an array of [atom0 atom1 atom2 atom3] (with atom1 and atom2 being the "rotor atoms" and the others being the dihedral atoms) and the value is a Collection of atoms IDs associated with atom2
//note that at this stage, there is no check to make sure that the dihedral atoms are not collinear
public LinkedHashMap getInternalRotorInformation(){
LinkedHashMap rotorInfo = new LinkedHashMap();
Graph g = getGraph();
for (Iterator iter = g.getArcList(); iter.hasNext();) {
Arc a = (Arc)iter.next();
Bond bond = (Bond)a.getElement();
if (bond.isSingle() && !a.getInCycle()) {
Iterator atomIter = a.getNeighbor();
Node n1 = (Node)atomIter.next();
Node n2 = (Node)atomIter.next();
if (!n1.isLeaf() && !n2.isLeaf()) {
//rotor++;
//above here is the rotor identification algorithm; below here is the code that stores the necessary information about the rotor
Graph f=Graph.copy(g);//copy the graph so we don't modify the original
f.removeArc(f.getArcBetween(n1.getID(), n2.getID()));//this should separate the graph into disconnected pieces (unless it is part of a cycle; if it is part of a cycle, however, this section of code shouldn't be reached)
LinkedList pieces = f.partitionWithPreservedIDs();//partition into the two separate graphs
Graph sideA = (Graph)pieces.getFirst();
Graph sideB = (Graph)pieces.getLast();
//look for the piece that has node2
if(sideA.getNodeIDs().contains(n2.getID())){
Node atom1 = sideB.getNodeAt(n1.getID());
Node atom2 = sideA.getNodeAt(n2.getID());
Node dihedral1 = (Node)atom1.getNeighboringNodes().iterator().next();//get a neighboring node
Node dihedral2 = (Node)atom2.getNeighboringNodes().iterator().next();//get a neighboring node
int rotorSym = calculateRotorSymmetryNumber(atom1,atom2);
int[] rotorAtoms = {dihedral1.getID(), n1.getID(), n2.getID(), dihedral2.getID(), rotorSym};
rotorInfo.put(rotorAtoms, sideA.getNodeIDs());
}
else if (sideB.getNodeIDs().contains(n2.getID())){
Node atom1 = sideA.getNodeAt(n1.getID());
Node atom2 = sideB.getNodeAt(n2.getID());
Node dihedral1 = (Node)atom1.getNeighboringNodes().iterator().next();//get a neighboring node
Node dihedral2 = (Node)atom2.getNeighboringNodes().iterator().next();//get a neighboring node
int rotorSym = calculateRotorSymmetryNumber(atom1,atom2);
int[] rotorAtoms = {dihedral1.getID(), n1.getID(), n2.getID(), dihedral2.getID(), rotorSym};
rotorInfo.put(rotorAtoms, sideB.getNodeIDs());
}
else{
Logger.critical("Error in getInternalRotorInformation(): Cannot find node "+ n2.getID()+" after splitting from "+ n1.getID() +" in the following graph:\n"+ g.toString());
System.exit(0);
}
}
}
}
return rotorInfo;
}
// ## operation isLinear()
public boolean isLinear() {
//#[ operation isLinear()
// only check for linearity in molecules with at least two atoms
if (getAtomNumber() == 1) return false;
// cyclic molecules are not linear
if (!isAcyclic()) return false;
// biatomic molecules are always linear
if (getAtomNumber() == 2) return true;
// molecules with only double bonds are linear (e.g. CO2)
boolean allDouble = true;
Iterator iter = getArcList();
while (iter.hasNext()) {
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (!bond.isDouble()) allDouble = false;
}
if (allDouble) return true;
// molecule with alternating single and triple bonds are linear (e.g. acetylene)
boolean alternatingSingleTriple = true;
Iterator node_iter = getNodeList();
while (node_iter.hasNext()) {
Node node = (Node)node_iter.next();
int neighborNumber = node.getNeighborNumber();
if (neighborNumber == 2) {
Iterator neighbor_iter = node.getNeighbor();
Arc a1 = (Arc)neighbor_iter.next();
Bond b1 = (Bond)a1.getElement();
Arc a2 = (Arc)neighbor_iter.next();
Bond b2 = (Bond)a2.getElement();
if (! ((b1.isTriple() && b2.isSingle()) || (b1.isSingle() && b2.isTriple())))
alternatingSingleTriple = false;
}
else if (neighborNumber > 2)
alternatingSingleTriple = false;
}
if (alternatingSingleTriple) return true;
// if none of the above are true, it's nonlinear
return false;
//#]
}
/**
Requires:
Effects: return S(T)
Modifies:
*/
//## operation calculateS(Temperature)
public double calculateS(Temperature p_temperature) {
//#[ operation calculateS(Temperature)
return getThermoData().calculateS(p_temperature);
//#]
}
//## operation calculateSymmetryNumber()
public int calculateSymmetryNumber() {
//#[ operation calculateSymmetryNumber()
try {
getGraph().formSSSR();//svp
int sn = 1;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
if (!node.getInCycle()){//svp
sn *= calculateAtomSymmetryNumber(node);
}
}
iter = getArcList();
while (iter.hasNext()) {
Arc arc = (Arc)iter.next();
if (!arc.getInCycle()){//svp
sn *= calculateBondSymmetryNumber(arc);
}
}
sn *= calculateAxisSymmetryNumber();
if (!isAcyclic()) {//svp
sn *= calculateCyclicSymmetryNumber();
}
symmetryNumber = sn;
return sn;
}
catch (ClassCastException e) {
throw new InvalidChemGraphException();
}
//#]
}
/**
Requies:
Effects: check if p_arc bond is the single bond between two Oxygens, which is considered as optical isomers
Modifies:
*/
//## operation checkOpticalIsomer(Arc)
public boolean checkOpticalIsomer(Arc p_arc) {
//#[ operation checkOpticalIsomer(Arc)
// check if the p_arc is -O-O-
Bond b = (Bond)p_arc.getElement();
if (b.isSingle()) {
Iterator neighbor_iter = p_arc.getNeighbor();
Node n1 = (Node)neighbor_iter.next();
Node n2 = (Node)neighbor_iter.next();
Atom a1 = (Atom)n1.getElement();
Atom a2 = (Atom)n2.getElement();
FGElement fge1 = (FGElement)n1.getFgElement();
FGElement fge2 = (FGElement)n2.getFgElement();
if (!a1.isRadical() && fge1.equals(FGElement.make("Os")) && !a2.isRadical() && fge2.equals(FGElement.make("Os"))) {
return true;
}
// else if (!a1.isRadical() && fge1.equals(FGElement.make("Sis")) && !a2.isRadical() && fge2.equals(FGElement.make("Sis"))) {
// return true;
// }
}
return false;
//#]
}
/**
Requires:
Effects: clear the central node list
Modifies:
*/
//## operation clearCentralNode()
public void clearCentralNode() {
//#[ operation clearCentralNode()
getGraph().clearCentralNode();
//#]
}
/**
Requires:
Effects: return a new instance identical to this ChemGraph
Modifies:
*/
//## operation copy(ChemGraph)
public static ChemGraph copy(ChemGraph p_chemGraph) throws ForbiddenStructureException {
Graph g = Graph.copy(p_chemGraph.getGraph());
ChemGraph cg = new ChemGraph(g);
cg.uniqueString = p_chemGraph.getUniqueString();
cg.chemicalFormula = p_chemGraph.getChemicalFormula();
cg.species = p_chemGraph.getSpecies();
cg.symmetryNumber = p_chemGraph.symmetryNumber;
cg.thermoData = p_chemGraph.thermoData;
cg.thermoGAPP = p_chemGraph.thermoGAPP;
cg.InChI = p_chemGraph.InChI;
cg.internalRotor = p_chemGraph.internalRotor;
cg.solvthermoData = p_chemGraph.solvthermoData;
/*HashSet oldSymmetryAxis = p_chemGraph.getSymmetryAxis();
if (oldSymmetryAxis != null) {
cg.symmetryAxis = new HashSet();
for (Iterator iAxis = oldSymmetryAxis.iterator(); iAxis.hasNext(); ) {
HashSet newAxis = new HashSet();
HashSet oldAxis = (HashSet)iAxis.next();
for (Iterator iArc = oldAxis.iterator(); iArc.hasNext(); ) {
Arc arc = (Arc)iArc.next();
Iterator iNode = arc.getNeighbor();
int n1 = ((Node)iNode.next()).getID().intValue();
int n2 = ((Node)iNode.next()).getID().intValue();
Arc newArc = cg.getArcBetween(n1,n2);
newAxis.add(newArc);
}
cg.symmetryAxis.add(newAxis);
}
}*/
return cg;
}
/**
Requires:
Effects: return true iff two chemgraph have equivalent graph structures
Modifies:
*/
//## operation equals(Object)
public boolean equals(Object p_chemGraph) {
//#[ operation equals(Object)
if (this == p_chemGraph) return true;
return isEquivalent((ChemGraph)p_chemGraph);
//#]
}
/**
Requires:
Effects: generate the chemical formula of this chem graph and return it. if the graph is not initialized, return null.
Modifies:
*/
//## operation generateChemicalFormula()
public String generateChemicalFormula() {
//#[ operation generateChemicalFormula()
if (getGraph() == null) return null;
/*int cap = ChemElementDictionary.size();
Vector type = new Vector(cap);
int[] number = new int[cap];
*/
int C_number = 0;
int H_number = 0;
int O_number = 0;
int radical = 0;
// Added by MRH on 18-Jun-2009
// Hardcoding Si and S into RMG-java
int Si_number = 0;
int S_number = 0;
int Cl_number = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
radical += atom.getRadicalNumber();
if (atom.isCarbon()) {
C_number++;
}
else if (atom.isHydrogen()) {
H_number++;
}
else if (atom.isOxygen()) {
O_number++;
}
// Added by MRH on 18-Jun-2009
// Hardcoding Si and S into RMG-java
else if (atom.isSilicon()) {
Si_number++;
}
else if (atom.isSulfur()) {
S_number++;
}
else if (atom.isChlorine()) {
Cl_number++;
}
else {
throw new InvalidChemNodeElementException();
}
}
String s = "";
if (C_number>0) {
s = s + "C";
if (C_number >1) {
s = s + String.valueOf(C_number);
}
}
if (H_number>0) {
s = s + "H";
if (H_number >1) {
s = s + String.valueOf(H_number);
}
}
if (O_number>0) {
s = s + "O";
if (O_number >1) {
s = s + String.valueOf(O_number);
}
}
// Added by MRH on 18-Jun-2009
// Hardcoding Si and S into RMG-java
if (Si_number>0) {
s += "Si";
if (Si_number>1) {
s += String.valueOf(Si_number);
}
}
if (S_number>0) {
s += "S";
if (S_number>1) {
s += String.valueOf(S_number);
}
}
chemicalFormula = s;
if (radical == 1) {
chemicalFormula = chemicalFormula + "J";
}
else if (radical == 2) {
chemicalFormula = chemicalFormula + "JJ";
}
else if (radical == 3) {
chemicalFormula = chemicalFormula + "JJJ";
}
return chemicalFormula;
//#]
}
//6/9/09 gmagoon: modified to also generate InChIKey; see comments in corresponding Species function
public String [] generateInChI() {
String [] result = Species.generateInChI(this);
InChI = result[0];
InChIKey = result[1];
return result;
}
public String generateMolFileString() {
String mfs = Species.generateMolFileString(this,4);//use 4 for benzene bond type...this is apparently not part of MDL MOL file spec, but seems to be more-or-less of a de facto standard, and seems to be properly processed by RDKit (cf. http://sourceforge.net/mailarchive/forum.php?forum_name=inchi-discuss&max_rows=25&style=nested&viewmonth=200909 )
//note that for aromatic radicals (e.g. phenyl), this produces an RDKit error, as shown below (at least using the (somewhat old) RDKit on gmagoon's laptop as of 9/12/11), but it still seems to process correctly, though the guess geometry isn't that great (more like sp3 than sp2); in practice, we won't often be using radicals with RDKit (exceptions include when requested by user or in DictionaryReader), so this shouldn't be a big deal
//ERROR: Traceback (most recent call last):
//ERROR: File "c:\Users\User1\RMG-Java/scripts/distGeomScriptMolLowestEnergyConf.py", line 13, in <module>
//ERROR: AllChem.EmbedMultipleConfs(m, attempts,randomSeed=1)
//ERROR: Boost.Python.ArgumentError: Python argument types in
//ERROR: rdkit.Chem.rdDistGeom.EmbedMultipleConfs(NoneType, int)
//ERROR: did not match C++ signature:
//ERROR: EmbedMultipleConfs(class RDKit::ROMol {lvalue} mol, unsigned int numConfs=10, unsigned int maxAttempts=0, int randomSeed=-1, bool clearConfs=True, bool useRandomCoords=False, double boxSizeMult=2.0, bool randNegEig=True, unsigned int numZeroFail=1, double pruneRmsThresh=-1.0, class boost::python::dict {lvalue} coordMap={})
//an alternative would be to use bond type of 1, which also seems to work, though the guess geometry for non-radicals (e.g. benzene) is not great (sp3 hybridized rather than sp2 hybridized)
return mfs;
}
/**
Requires:
Effects: if the thermoGAPP is not set, set default GAPP. Use it to calculate the thermoData of this chem graph. if there is any exception during this process, throw FailGenerateThermoDataException.
Modifies: this.thermoData
*/
//## operation generateThermoData()
public ThermoData generateThermoData() throws FailGenerateThermoDataException {
//#[ operation generateThermoData()
// use GAPP to generate Thermo data
try {
if (useQM){
if(useQMonCyclicsOnly && this.isAcyclic()) thermoGAPP=GATP.getINSTANCE();//use GroupAdditivity for acyclic compounds if this option is set
else thermoGAPP=QMTP.getINSTANCE();
}
else if (thermoGAPP == null) setDefaultThermoGAPP();
thermoData = thermoGAPP.generateThermoData(this);
//fall back to GATP if it is a failed QMTP calculation
if (((String)thermoData.getSource()).equals("***failed calculation***")){
Logger.warning("Falling back to group additivity due to repeated failure in QMTP calculations");
thermoData=(GATP.getINSTANCE()).generateThermoData(this);
}
//thermoData = thermoGAPP.generateAbramData(this);
return thermoData;
}
catch (MultipleGroupFoundException e) {
throw e;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new FailGenerateThermoDataException();
}
//#]
}
public TransportData generateTransportData() {
if (transportGAPP == null) setDefaultTransportGAPP();
transportData = transportGAPP.generateTransportData(this);
return transportData;
}
// Amrit Jalan 05/09/2009
public ThermoData generateSolvThermoData() throws FailGenerateThermoDataException {
// use GAPP to generate Thermo data
try {
if (SolvationGAPP == null) setDefaultSolvationGAPP();
solvthermoData = SolvationGAPP.generateSolvThermoData(this);
return solvthermoData;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new FailGenerateThermoDataException();
}
}
public AbramData generateAbramData() throws FailGenerateThermoDataException {
// use GAPP to generate Thermo data
try {
if (abramGAPP == null) setDefaultAbramGAPP();
abramData = abramGAPP.generateAbramData(this);
return abramData;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new FailGenerateThermoDataException();
}
}
public UnifacData generateUnifacData() throws FailGenerateThermoDataException {
try {
if (unifacGAPP == null) setDefaultUnifacGAPP();
unifacData = unifacGAPP.generateUnifacData(this);
return unifacData;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new FailGenerateThermoDataException();
}
}
/**
Requires:
Effects: return the Arc between two positions in this ChemGraph
Modifies:
*/
public Arc getArcBetween(int p_position1, int p_position2) {
return getGraph().getArcBetween(p_position1,p_position2);
}
/**
Requires:
Effects: return an arc iterator of this ChemGraph
Modifies:
*/
//## operation getArcList()
public Iterator getArcList() {
//#[ operation getArcList()
return getGraph().getArcList();
//#]
}
/**
Requires:
Effects: return the atom at the p_position in this chem graph; if p_position is empty, return null;
Modifies:
*/
//## operation getAtomAt(int)
public Atom getAtomAt(int p_position) throws EmptyAtomException {
//#[ operation getAtomAt(int)
try {
return (Atom)(getNodeAt(p_position).getElement());
}
catch (NotInGraphException e) {
return null;
}
//#]
}
/**
Requires:
Effects: return the total atom number in this ChemGraph.
Modifies:
*/
//## operation getAtomNumber()
public int getAtomNumber() {
//#[ operation getAtomNumber()
return getGraph().getNodeNumber();
//#]
}
/**
Requires:
Effects: if there is a bond connecting p_position1 and p_position2, return that bond; otherwise, return null.
Modifies:
*/
//## operation getBondBetween(int,int)
public Bond getBondBetween(int p_position1, int p_position2) throws EmptyAtomException {
//#[ operation getBondBetween(int,int)
try {
return (Bond)(getArcBetween(p_position1,p_position2).getElement());
}
catch (ClassCastException e) {
return null;
}
//#]
}
//## operation getCarbonNumber()
public int getCarbonNumber() {
//#[ operation getCarbonNumber()
int cNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isCarbon()) {
cNum++;
}
}
return cNum;
//#]
}
/**
Requires:
Effects: return the hashMap of centralNode in this ChemGraph
Modifies:
*/
//## operation getCentralNode()
public LinkedHashMap getCentralNode() {
//#[ operation getCentralNode()
return getGraph().getCentralNode();
//#]
}
/**
Requires:
Effects: return the node whose centralID equals p_position
Modifies:
*/
//## operation getCentralNodeAt(int)
public Node getCentralNodeAt(int p_position) {
//#[ operation getCentralNodeAt(int)
return getGraph().getCentralNodeAt(p_position);
//#]
}
/**
Requires:
Effects: return the number of the central nodes in this chem graph
Modifies:
*/
//## operation getCentralNodeNumber()
public int getCentralNodeNumber() {
//#[ operation getCentralNodeNumber()
return getGraph().getCentralNodeNumber();
//#]
}
//## operation getChemicalFormula()
public String getChemicalFormula() {
//#[ operation getChemicalFormula()
if (chemicalFormula == null || chemicalFormula.length() == 0) generateChemicalFormula();
return chemicalFormula;
//#]
}
/**
Requires:
Effects: return the iterator loop over the graph's cycle list.
Modifies:
*/
//## operation getCycle()
public Iterator getCycle() {
//#[ operation getCycle()
return getGraph().getCycle().iterator();
//#]
}
public int getCycleNumber(){
return getGraph().getCycleNumber();
}
//## operation getHydrogenNumber()
public int getHydrogenNumber() {
//#[ operation getHydrogenNumber()
int hNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isHydrogen()) {
hNum++;
}
}
return hNum;
//#]
}
public String getInChI() {
if (InChI == null || InChI.length() == 0) generateInChI();
return InChI;
}
public String getInChIKey() {
if (InChIKey == null || InChIKey.length() == 0) generateInChI();
return InChIKey;
}
//gmagoon 7/25/09: same as above function, except it will replace an existing InChI; this is useful when ChemGraph changes (e.g. during HBI process)
public String getInChIAnew() {
generateInChI();
return InChI;
}
//gmagoon 7/25/09: same as above function, except it will replace an existing InChIKey; this is useful when ChemGraph changes (e.g. during HBI process)
public String getInChIKeyAnew() {
generateInChI();
return InChIKey;
}
//gmagoon 9/1/09: these functions (getModifiedInChIAnew and getModifiedInChIKeyAnew) do the same as above, except return a modified version of the InChI and InChIKey with an indication of the multiplicity based on the number of radicals if the number of radicals is 2 or greater
public String getModifiedInChIAnew(){
generateInChI();
String newInChI=null;
int radicalNumber = this.getUnpairedRadicalNumber();
// System.out.println("Radical number:"+radicalNumber);//for debugging purposes
if (radicalNumber >= 2){
newInChI = InChI.concat("/mult"+(radicalNumber+1));
}
else{
newInChI = InChI;
}
return newInChI;
}
public String getModifiedInChIKeyAnew(){
generateInChI();
String newInChIKey=null;
int radicalNumber = this.getUnpairedRadicalNumber();
// System.out.println("Radical number:"+radicalNumber);//for debugging purposes
if (radicalNumber >= 2){
newInChIKey = InChIKey.concat("mult"+(radicalNumber+1));
}
else{
newInChIKey= InChIKey;
}
return newInChIKey;
}
/**
Requires:
Effects: add the weight of all the atoms in this graph to calculate the molecular weight of this chem graph
Modifies:
*/
//## operation getMolecularWeight()
public double getMolecularWeight() {
//#[ operation getMolecularWeight()
double MW = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
MW += ((Atom)(node.getElement())).getWeight();
}
return MW;
//#]
}
/**
Requires:
Effects: return the "legal" name of this ChemGraph. The order of priority
(1) uniqueString
(2) species.name
(3) chemicalFormula
Modifies:
*/
//## operation getName()
public String getName() {
//#[ operation getName()
if (uniqueString != null && uniqueString.length() > 0) return uniqueString;
String name = getSpecies().getName();
if (name != null && name.length() > 0) return name;
return getChemicalFormula();
//#]
}
/**
Requires:
Effects: return the node whose ID equals p_position.
Modifies:
*/
//## operation getNodeAt(int)
public Node getNodeAt(int p_position) {
//#[ operation getNodeAt(int)
return getGraph().getNodeAt(p_position);
//#]
}
/**
Requires:
Effects: return the node whose ID equals p_ID.
Modifies:
*/
//## operation getNodeAt(Integer)
public Node getNodeAt(Integer p_ID) {
//#[ operation getNodeAt(Integer)
return getGraph().getNodeAt(p_ID);
//#]
}
/**
Requires:
Effects: return an iterator over the node collection of this graph
Modifies:
*/
//## operation getNodeList()
public Iterator getNodeList() {
//#[ operation getNodeList()
return getGraph().getNodeList();
//#]
}
public int getDoubleBonds(){
int dBond = 0;
Iterator iter = getArcList();
while (iter.hasNext()){
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (bond.order==2){
dBond++;
}
}
return dBond;
}
public int getSingleBonds(){
int sBond = 0;
Iterator iter = getArcList();
while (iter.hasNext()){
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (bond.order==1){
sBond++;
}
}
return sBond;
}
public int getTripleBonds(){
int tBond = 0;
Iterator iter = getArcList();
while (iter.hasNext()){
Arc arc = (Arc)iter.next();
Bond bond = (Bond)arc.getElement();
if (bond.order==3){
tBond++;
}
}
return tBond;
}
//## operation getOxygenNumber()
public int getOxygenNumber() {
//#[ operation getOxygenNumber()
int oNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isOxygen()) {
oNum++;
}
}
return oNum;
//#]
}
/**
Requires:
Effects: return a collection of all the radical sites
Modifies:
*/
//## operation getRadicalNode()
public LinkedHashSet getRadicalNode() {
//#[ operation getRadicalNode()
LinkedHashSet radicalNode = new LinkedHashSet();
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node n = (Node)iter.next();
Atom a = (Atom)n.getElement();
if (a.isRadical()) {
radicalNode.add(n);
}
}
return radicalNode;
//#]
}
/**
Requires:
Effects: calculate the total radical number in this chem graph.
Modifies:
*/
//## operation getRadicalNumber()
public int getRadicalNumber() {
//#[ operation getRadicalNumber()
int radicalNumber = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Object element = ((Node)(iter.next())).getElement();
radicalNumber += ((Atom)element).getRadicalNumber();
}
return radicalNumber;
//#]
}
//gmagoon 4/30/10: modified version of getRadicalNumber; same as getRadicalNumber, except it will not count 2S as radical
public int getUnpairedRadicalNumber() {
int radicalNumber = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Object element = ((Node)(iter.next())).getElement();
radicalNumber += ((Atom)element).getUnpairedRadicalNumber();
}
return radicalNumber;
}
public int getSiliconNumber() {
int siNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isSilicon()) {
siNum++;
}
}
return siNum;
}
public int getSulfurNumber() {
int sNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isSulfur()) {
sNum++;
}
}
return sNum;
}
public int getChlorineNumber() {
int ClNum = 0;
Iterator iter = getNodeList();
while (iter.hasNext()) {
Node node = (Node)iter.next();
Atom atom = (Atom)node.getElement();
if (atom.isChlorine()) {
ClNum++;
}
}
return ClNum;
}
//## operation getSymmetryNumber()
public int getSymmetryNumber() {
//#[ operation getSymmetryNumber()
if (symmetryNumber < 0) calculateSymmetryNumber();
return symmetryNumber;
//#]
}
//## operation getThermoData()
public ThermoData getThermoData() {
//#[ operation getThermoData()
if (thermoData == null)
{
generateThermoData();
// thermoData is brand new gas phase estimate
if (Species.useSolvation) {
if (solvthermoData==null) generateSolvThermoData();
// solvthermoData is estimate of correction
thermoData.plus(solvthermoData);
thermoData.comments+=" corrected for solvation";
// thermoData is corrected
}
}
return thermoData;
//#]
}
public TransportData getTransportData() {
if (transportData == null) generateTransportData();
return transportData;
}
//## operation getThermoData()
public ThermoData getSolvationData() {
//#[ operation getThermoData()
if (solvthermoData == null) generateSolvThermoData();
return solvthermoData;
//#]
}
public AbramData getAbramData() {
//#[ operation getThermoData()
if (abramData == null) generateAbramData();
return abramData;
//#]
}
public UnifacData getUnifacData() {
//#[ operation getThermoData()
if (unifacData == null) generateUnifacData();
return unifacData;
//#]
}
/**
Added by: Amrit Jalan
Effects: calculate the raduis of the chemGraph using Abraham V values. (UNITS of radius = m)
*/
public double getRadius() {
double ri;
if (getCarbonNumber() == 0 && getOxygenNumber() == 0){ // Which means we ar dealing with HJ or H2
double ri3;
ri3 = 8.867 / 4.1887902; // 8.867 Ang^3 is the volume of a single Hydrogen Atom. 4.1887902 is 4pi/3
if (getHydrogenNumber() == 1){ // i.e. we are dealing with the Hydrogen radical
ri = Math.pow(ri3,0.333333) * 1.0e-10;
return ri;
}
if (getHydrogenNumber() == 2){ // i.e. we are dealing with the Hydrogen molecule
ri3 = 2*ri3; // Assumption: volume of H2 molecule ~ 2 * Volume of H atom
ri = Math.pow(ri3,0.333333) * 1.0e-10;
return ri;
}
}
double solute_V = getAbramData().V; //Units: cm3/100/mol
double volume = solute_V * 100 / 6.023e23; //Units: cm3/molecule
double ri3 = volume / 4.1887902 ; // Units: cm3 (4.1887902 is 4pi/3)
ri = Math.pow(ri3,0.333333)*0.01; //Returns the solute radius in 'm'
// double Ri=getUnifacData().R;
// ri=3.18*Math.pow(Ri,0.333333)*1.0e-10; // From Koojiman Ind. Eng. Chem. Res 2002, 41 3326-3328
return ri;
}
/**
Added by: Amrit Jalan
Effects: calculate the diffusivity of the chemGraph using radii, solvent viscosity and Stokes Einstein. (UNITS m2/sec)
*/
public double getDiffusivity() {
double speRad=getRadius();
Temperature sysTemp = ReactionModelGenerator.getTemp4BestKinetics();
//double solventViscosity = 9.65e-6 * Math.exp((811.75/sysTemp.getK()+(346920/sysTemp.getK()/sysTemp.getK()))); //Viscosity of octanol at a function of temperature. Obtained from Matsuo and Makita (INTERNATIONAL JOURNAL OF THERMOPHYSICSVolume 10, Number 4, 833-843, DOI: 10.1007/BF00514479)
//double solventViscosity = 0.136*Math.pow(10,-3); //Viscosity of liquid decane
//double solventViscosity = 0.546*Math.pow(10,-3); //Viscosity of liquid DMSO (dimethyl sulfoxide) Units: Pa.sec
//double solventViscosity = 0.6*Math.pow(10,-3); //Viscosity of liquid CH3CN Units: Pa.sec
//double solventViscosity = 1.122*Math.pow(10,-3); //Viscosity of liquid tetralin Source: International Journal of Thermophysics, Vol. 10, No. 4, 1989
//double solventViscosity = 0.404*Math.pow(10,-3); //Viscosity of water at 343 K
double solventViscosity = ReactionModelGenerator.getViscosity();
double denom = 132 * solventViscosity * speRad / 7;
double diffusivity = 1.381 * sysTemp.getK() * 1.0e-23 / denom; //sysTemp.getK()
return diffusivity;
}
/**
Requires:
Effects: find out the end of C=C=C... pattern
Modifies:
*/
//## operation getToEndOfAxis(Arc,Node,HashSet)
private static final Node getToEndOfAxis(Arc p_beginArc, Node p_beginNode, HashSet p_axis) {
//#[ operation getToEndOfAxis(Arc,Node,HashSet)
Arc nextArc = null;
Iterator iter = p_beginNode.getNeighbor();
while (iter.hasNext()) {
nextArc = (Arc)iter.next();
if (nextArc != p_beginArc) break;
}
p_axis.add(nextArc);
Node nextNode = nextArc.getOtherNode(p_beginNode);
FGElement fge = (FGElement)nextNode.getFgElement();
FGElement Cdd = FGElement.make("Cdd");
FGElement Sidd = FGElement.make("Sidd");
if (!fge.equals(Cdd) & !fge.equals(Sidd)) return nextNode;
else {
return getToEndOfAxis(nextArc,nextNode,p_axis);
}
//#]
}
//find the end of the Ct-Ct-Ct... pattern
//based on similar function getToEndOfAxis
private static final Node getToEndOfCumulatedTripleBondSystem(Arc p_beginArc, Node p_beginNode, HashSet p_axis) {
//#[ operation getToEndOfAxis(Arc,Node,HashSet)
Arc nextArc = null;
Iterator iter = p_beginNode.getNeighbor();
while (iter.hasNext()) {
nextArc = (Arc)iter.next();
if (nextArc != p_beginArc) break;
}
p_axis.add(nextArc);
Node nextNode = nextArc.getOtherNode(p_beginNode);
FGElement fge = (FGElement)nextNode.getFgElement();
FGElement Ct = FGElement.make("Ct");
if (!fge.equals(Ct)) return nextNode;
else {
return getToEndOfCumulatedTripleBondSystem(nextArc,nextNode,p_axis);
}
}
/**
Requires:
Effects: check if the element of every node is an atom, and if the element of every node is a bond.
Modifies:
*/
//## operation graphContentsOk(Graph)
public static boolean graphContentsOk(Graph p_graph) {
//#[ operation graphContentsOk(Graph)
Iterator iter = p_graph.getNodeList();
while (iter.hasNext()) {
Object atom = ((Node)iter.next()).getElement();
if (!(atom instanceof Atom)) return false;
}
iter = p_graph.getArcList();
while (iter.hasNext()) {
Object bond = ((Arc)iter.next()).getElement();
if (!(bond instanceof Bond)) return false;
}
return true;
//#]
}
/**
Requires:
Effects: return chemicalFormula's hashcode. i.e., all the isomers have the same hashcode
Modifies:
*/
//## operation hashCode()
public int hashCode() {
//#[ operation hashCode()
if (chemicalFormula == null) generateChemicalFormula();
return chemicalFormula.hashCode()+getTripleBonds()*300 + getSingleBonds()*1 + getDoubleBonds()*20;
//#]
}
/**
Requires:
Effects: check all the possible reacted sites in this chemgraph according to the pass-in functional group or functional group collection. If there are any matches, return all the matches in a linked list; otheriwse, return an empty list.
Modifies:
*/
//## operation identifyReactionMatchedSite(Matchable)
public LinkedHashSet identifyReactionMatchedSite(Matchable p_functionalGroup) {
//#[ operation identifyReactionMatchedSite(Matchable)
if (p_functionalGroup instanceof FunctionalGroup) {
FunctionalGroup fg = (FunctionalGroup)p_functionalGroup;
//boolean thisIsRadical = this.isRadical();
//boolean fgIsRadical = fg.isRadical();
//if (thisIsRadical == fgIsRadical) {
return getGraph().identifyAllOrderedMatchedSites(fg.getGraph());
//}
//else {
//return new LinkedHashSet();
//}
}
else if (p_functionalGroup instanceof FunctionalGroupCollection) {
LinkedHashSet result = new LinkedHashSet();
FunctionalGroupCollection fgc = (FunctionalGroupCollection)p_functionalGroup;
Iterator iter = fgc.getFunctionalGroups();
while (iter.hasNext()) {
FunctionalGroup fg = (FunctionalGroup)iter.next();
//boolean thisIsRadical = this.isRadical();
//boolean fgIsRadical = fg.isRadical();
//if (thisIsRadical == fgIsRadical) {
LinkedHashSet site = getGraph().identifyAllOrderedMatchedSites(fg.getGraph());
result.addAll(site);
//}
}
return result;
}
else {
throw new InvalidFunctionalGroupException();
}
//#]
}
/**
Requires:
Effects: get a collection of all the thermo matched site, this for corrections in GAPP.
Modifies:
*/
//## operation identifyThermoMatchedSite(FunctionalGroup)
public LinkedHashSet identifyThermoMatchedSite(FunctionalGroup p_functionalGroup) {
//#[ operation identifyThermoMatchedSite(FunctionalGroup)
return getGraph().identifyAllUnorderedMatchedSite(p_functionalGroup.getGraph());
//#]
}
/**
Requires:
Effects: return true if there is no cycle in the chem graph
Modifies:
*/
//## operation isAcyclic()
public boolean isAcyclic() {
//#[ operation isAcyclic()
return getGraph().isAcyclic();
//#]
}
/**
Requires:
Effects: return true iff this and p_chemGraph are equivalent chemgraphs.
Modifies:
*/
//## operation isEquivalent(ChemGraph)
public boolean isEquivalent(ChemGraph p_chemGraph) {
//#[ operation isEquivalent(ChemGraph)
if (chemicalFormula == null) generateChemicalFormula();
if (p_chemGraph.chemicalFormula == null) p_chemGraph.generateChemicalFormula();
if (!getChemicalFormula().equals(p_chemGraph.getChemicalFormula())) return false;
if (!getGraph().isEquivalent(p_chemGraph.getGraph())) return false;
return true;
//#]
}
/**
Requires:
Effects: return true iff this chemGraph contains forbidden structure.
Modifies:
*/
public static boolean isForbiddenStructure(Graph p_graph, int radNumber, int oNumber, int cNumber) {
/*Iterator iter = p_graph.getNodeList();
while (iter.hasNext()){
Node n = (Node)iter.next();
Atom atom = (Atom)n.getElement();
if (atom.isOxygen()) {
Iterator neighborarc = n.getNeighbor();
if (neighborarc.hasNext()){
Arc arc1 = (Arc)neighborarc.next();
if (neighborarc.hasNext()){
Node neighbornode1 = n.getOtherNode(arc1);
Arc arc2 = (Arc)neighborarc.next();
Node neighbornode2 = n.getOtherNode(arc2);
if (((Atom)neighbornode1.getElement()).isOxygen() && ((Atom)neighbornode2.getElement()).isOxygen())
return true;
}
}
}
}
return false;*/
for (Iterator iter = forbiddenStructure.iterator(); iter.hasNext(); ) {
FunctionalGroup fg = (FunctionalGroup)iter.next();
if (radNumber >= fg.rad_count && oNumber >= fg.O_count && cNumber >= fg.C_count) {
Graph g = fg.getGraph();
if (p_graph.isSub(g)) {
return true;
}
}
}
return false;
}
// Which forbidden structure forbade this chemgraph?
// returns the names of forbidden structures.
public static String whichForbiddenStructures(Graph p_graph, int radNumber, int oxygenNumber, int cycleNumber) {
String forbidden_by = "";
for (Iterator iter = forbiddenStructure.iterator(); iter.hasNext(); ) {
FunctionalGroup fg = (FunctionalGroup)iter.next();
Graph g = fg.getGraph();
if (p_graph.isSub(g)) {
forbidden_by += fg.getName() +", ";
}
}
if (forbidden_by=="") {
if (radNumber > MAX_RADICAL_NUM)
return "the maximum number of radicals per species (check the condition.txt file), ";
else if (oxygenNumber > MAX_OXYGEN_NUM)
return "the maximum number of oxygens per species (check the condition.txt file), ";
else if (cycleNumber > MAX_CYCLE_NUM)
return "the maximum number of cycles per species (check the condition.txt file), ";
else
return "no forbidden structures, ";
}
return forbidden_by;
}
/**
Requires:
Effects: return true iff this chemgraph contains radical site
Modifies:
*/
//## operation isRadical()
public boolean isRadical() {
//#[ operation isRadical()
return (getRadicalNumber() > 0);
//#]
}
/**
Requires:
Effects: if p_functionalGroup is a FunctionalGroup, return if this chemgraph is matched with it at the central nodes; if p_functionalGroup is a FunctionalGroupCollection, return if this chemgraph is matched with any of the functionalgroup in the collection at the central node. for all other case, return false.
Modifies:
*/
//## operation isSubAtCentralNodes(Matchable)
public boolean isSubAtCentralNodes(Matchable p_functional) {
//#[ operation isSubAtCentralNodes(Matchable)
if (this == p_functional) return false;
if (p_functional instanceof FunctionalGroup) {
return isSubAtCentralNodes((FunctionalGroup)p_functional);
}
else if (p_functional instanceof FunctionalGroupCollection) {
Iterator iter = ((FunctionalGroupCollection)p_functional).getFunctionalGroups();
while (iter.hasNext()) {
FunctionalGroup fg = (FunctionalGroup)iter.next();
if (isSubAtCentralNodes(fg)) return true;
}
return false;
}
else {
return false;
}
//#]
}
/**
Requires: both graph components belong to the same graph
Effects: return true if two graph components are equal
Modifies:
svp
*/
//## operation isSymmetric(GraphComponent, GraphComponent)
public boolean isSymmetric(GraphComponent p_gc1, GraphComponent p_gc2) {
//#[ operation isSymmetric(GraphComponent, GraphComponent)
Stack s1 = new Stack();
Stack s2 = new Stack();
if (p_gc1.isEquivalent(p_gc2, s1, s2)) {
resetStack(s1);
resetStack(s2);
getGraph().resetMatchedGC();
return true;
}
else {
resetStack(s1);
resetStack(s2);
getGraph().resetMatchedGC();
return false;
}
//#]
}
/**
Requires:
Effects: return if this chem graph is matched with p_functionalGroup at the central nodes.
Modifies:
*/
//## operation isSubAtCentralNodes(FunctionalGroup)
public boolean isSubAtCentralNodes(FunctionalGroup p_functionalGroup) {
//#[ operation isSubAtCentralNodes(FunctionalGroup)
return getGraph().isSubAtCentralNodes(p_functionalGroup.getGraph());
//#]
}
/**
Requires:
Effects: factory method for ChemGraph. make a new instance of ChemGraph. Do such things for it:
(1) add missing H
(2) generate chemical formula
(3) calculate symmetry number
(4) calculate thermal properties
Modifies:
*/
//## operation make(Graph)
/*public static ChemGraph make(Graph p_graph) throws InvalidChemGraphException, ForbiddenStructureException {
//#[ operation make(Graph)
double pT = System.currentTimeMillis();
Global.makeChemG++;
Species sp = SpeciesDictionary.getInstance().getSpeciesFromGraph(p_graph);
ChemGraph cg = null;
if (sp !=null){
if (sp.hasResonanceIsomers()){
Iterator rIter = sp.getResonanceIsomers();
while(rIter.hasNext()){
ChemGraph chemGraph = (ChemGraph)rIter.next();
if (chemGraph.graph.equals(p_graph)){
chemGraph.graph = p_graph;
return chemGraph;
}
}
}
else {
sp.chemGraph.graph = p_graph;
return sp.chemGraph;
}
}
if (cg == null){
try {
cg = new ChemGraph(p_graph);
cg.addMissingHydrogen();
if (cg.repOk()){
cg.generateChemicalFormula();
//cg.calculateSymmetryNumber();
Global.symmetryCG+=(System.currentTimeMillis()-pT)/1000/60;
pT = System.currentTimeMillis();
//cg.generateThermoData();
Global.thermoCG += (System.currentTimeMillis()-pT)/1000/60;
pT = System.currentTimeMillis();
//cg.calculateInternalRotor();
}
else {
throw new InvalidChemGraphException();
}
}
catch (ForbiddenStructureException e) {
throw new ForbiddenStructureException(e.getMessage());
}
}
Global.IRCG+=(System.currentTimeMillis()-pT)/1000/60;
return cg;
//#]
}*/
public static ChemGraph make(Graph p_graph, boolean hasHydrogen) throws InvalidChemGraphException, ForbiddenStructureException {
//#[ operation make(Graph)
double pT = System.currentTimeMillis();
ChemGraph cg = null;
if (cg == null){
cg = new ChemGraph(p_graph);
if (!hasHydrogen)
cg.addMissingHydrogen();
if (cg.repOk()){
cg.generateChemicalFormula();
}
else {
throw new InvalidChemGraphException();
}
//cgd.putSpecies(cg);
}
return cg;
//#]
}
public static ChemGraph make(Graph p_graph) throws InvalidChemGraphException, ForbiddenStructureException {
//#[ operation make(Graph)
double pT = System.currentTimeMillis();
//ChemGraphDictionary cgd = ChemGraphDictionary.getInstance();
ChemGraph cg = null;//= cgd.getChemGraphFromGraph(p_graph);
if (cg == null){
cg = new ChemGraph(p_graph);
cg.addMissingHydrogen();
if (cg.repOk()){
cg.generateChemicalFormula();
}
else {
Logger.error(getRepOkString());
throw new InvalidChemGraphException();
}
//cgd.putSpecies(cg);
}
return cg;
//#]
}
public static void addForbiddenStructure(FunctionalGroup fg) {
forbiddenStructure.add(fg);
}
/**
Requires:
Effects: read in forbidden structure for ChemGraph
Modifies: this.forbiddenStructure
*/
//## operation readForbiddenStructure()
public static void readForbiddenStructure() throws IOException {
//#[ operation readForbiddenStructure()
try {
String forbiddenStructureFile = System.getProperty("jing.chem.ChemGraph.forbiddenStructureFile");
if (forbiddenStructureFile == null) {
Logger.error("Undefined system property: jing.chem.ChemGraph.forbiddenStructureFile!");
Logger.error("No forbidden structure file defined!");
throw new IOException("Undefined system property: jing.chem.ChemGraph.forbiddenStructureFile");
//return;
}
FileReader in = new FileReader(forbiddenStructureFile);
BufferedReader data = new BufferedReader(in);
// step 1: read in structure
String line = ChemParser.readMeaningfulLine(data, true);
read: while (line != null) {
StringTokenizer token = new StringTokenizer(line);
String fgname = token.nextToken();
Graph fgGraph = null;
try {
fgGraph = ChemParser.readFGGraph(data);
}
catch (InvalidGraphFormatException e) {
throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage());
}
if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname);
//FunctionalGroup fg = FunctionalGroup.make(fgname, fgGraph);
FunctionalGroup fg = FunctionalGroup.makeForbiddenStructureFG(fgname, fgGraph);
forbiddenStructure.add(fg);
line = ChemParser.readMeaningfulLine(data, true);
}
in.close();
return;
}
catch (Exception e) {
Logger.logStackTrace(e);
throw new IOException(e.getMessage());
}
//#]
}
/**
Requires:
Effects: reset centralNode list in this ChemGraph according to node's CentralID information
Modifies: this.graph.centralNode
*/
//## operation refreshCentralNode()
public void refreshCentralNode() {
//#[ operation refreshCentralNode()
getGraph().refreshCentralNode();
//#]
}
/**
Requires:
Effects: check four aspects:
(1) if graph.repOk() defined in Graph class
(2) if graph is connected
(3) if the graph contents are atoms and bonds
(4) if the valency are okay for all atom
(5) if the radical number is in the limit
*/
//## operation repOk()
public boolean repOk() {
//#[ operation repOk()
// check if the graph is connected
if (!getGraph().repOk()){
setRepOkString("Something is wrong with the following chemgraph: " + this.toString());
return false;
}
// a chemical species should be a connected graph
if (!getGraph().isConnected()) {
setRepOkString("The following chemgraph is not a connected graph: " + this.toString());
return false;
}
// check if the elements stored in graph are atomd/bonds
if (!graphContentsOk(getGraph())) {
setRepOkString("The following chemgraph contains contents other than atoms or bonds: " + this.toString());
return false;
}
// check if the valency of every atom is satuated
//if (!valencyOk()) return false;
// check if the radical number greater than MAX_RADICAL_NUM
if (getRadicalNumber() > MAX_RADICAL_NUM) {
setRepOkString("The following chemgraph exceeds the maximum radicals allowed in a species: " + this.toString());
return false;
}
// check if the oxygen atom number is too large
if (getOxygenNumber() > MAX_OXYGEN_NUM) {
setRepOkString("The following chemgraph exceeds the maximum oxygens allowed (" + MAX_OXYGEN_NUM + ") in a species:\n" + this.toString());
return false;
}
if (getCarbonNumber() > MAX_CARBON_NUM) {
setRepOkString("The following chemgraph exceeds the maximum carbons allowed (" + MAX_CARBON_NUM + ") in a species:\n" + this.toString());
return false;
}
if (getSulfurNumber() > MAX_SULFUR_NUM) {
setRepOkString("The following chemgraph exceeds the maximum sulfurs allowed (" + MAX_SULFUR_NUM + ") in a species:\n" + this.toString());
return false;
}
if (getSiliconNumber() > MAX_SILICON_NUM) {
setRepOkString("The following chemgraph exceeds the maximum silicons allowed (" + MAX_SILICON_NUM + ") in a species:\n" + this.toString());
return false;
}
if (getHeavyAtomNumber() > MAX_HEAVYATOM_NUM) {
setRepOkString("The following chemgraph exceeds the maximum heavy atoms allowed (" + MAX_HEAVYATOM_NUM + ") in a species:\n" + this.toString());
return false;
}
return true;
//#]
}
/**
Requires:
Effects: reset reacting site as the pass-in p_site.
Modifies: this.graph.centralNode
*/
//## operation resetReactedSite(HashMap)
public void resetReactedSite(HashMap p_site) throws SiteNotInSpeciesException {
//#[ operation resetReactedSite(HashMap)
setCentralNode(p_site);
//#]
}
//## operation resetStack(Stack)
//svp
public void resetStack(Stack p_stack) {
//#[ operation resetStack(Stack)
while (!p_stack.empty()) {
GraphComponent gc = (GraphComponent)p_stack.pop();
gc.setMatchedGC(null);
}
return;
//#]
}
/**
Requires:
Effects: reset the only center to the p_node in this chem graph for thermo calculation
Modifies: this.graph.centralNode, and centralIDs in its associated nodes.
*/
//## operation resetThermoSite(Node)
public void resetThermoSite(Node p_node) {
//#[ operation resetThermoSite(Node)
getGraph().clearCentralNode();
getGraph().setCentralNode(1,p_node);
return;
//#]
}
/**
Requires:
Effects: reset centreNode list as the pass-in p_site.
Modifies: this.graph.centralNode
*/
//## operation setCentralNode(HashMap)
protected void setCentralNode(HashMap p_site) {
//#[ operation setCentralNode(HashMap)
try {
Graph g = getGraph();
g.clearCentralNode();
g.setCentralNodes(p_site);
}
catch (NotInGraphException e) {
throw new SiteNotInSpeciesException();
}
//#]
}
/**
Requires:
Effects: set GTPP as the thermoGAPP of this chem graph
Modifies: thermoGAPP
*/
//## operation setDefaultThermoGAPP()
public void setDefaultThermoGAPP() {
//#[ operation setDefaultThermoGAPP()
thermoGAPP = GATP.getINSTANCE();
return;
//#]
}
public void setDefaultTransportGAPP() {
transportGAPP = GATransportP.getINSTANCE();
return;
}
public void setDefaultSolvationGAPP() {
//#[ operation setDefaultThermoGAPP()
SolvationGAPP = GATP_Solvation.getINSTANCE();
return;
//#]
}
public void setDefaultAbramGAPP() {
//#[ operation setDefaultThermoGAPP()
abramGAPP = GATP_Abraham.getINSTANCE();
return;
//#]
}
public void setDefaultUnifacGAPP() {
//#[ operation setDefaultThermoGAPP()
unifacGAPP = GATP_Unifac.getINSTANCE();
return;
//#]
}
/**
Requires:
Effects: return a string of this chemgraph. the string includes two parts:
(1) chemical formula
(2) the string for the graph
Modifies:
*/
//## operation toString()
public String toString() {
//#[ operation toString()
String s = "ChemFormula: " + getChemicalFormula() + '\n';
s = s + getGraph().toStringWithoutCentralID();
return s;
//#]
}
public String toString(int i) {
//#[ operation toString()
String s ="";// "ChemFormula: " + getChemicalFormula() + '\n';
s = s + getGraph().toStringWithoutCentralID();
return s;
//#]
}
/**
Requires:
Effects: return a short string for this ChemGraph. it includes two parts:
(1) chemical formula
(2) the graph string without H
Modifies:
*/
//## operation toStringWithoutH()
public String toStringWithoutH() {
//#[ operation toStringWithoutH()
String s = "ChemFormula: " + getChemicalFormula() + '\n';
if (getHeavyAtomNumber() == 0)
s += getGraph().toStringWithoutCentralID();
else
s = s + getGraph().toStringWithoutCentralIDAndH();
return s;
//#]
}
/**
Requires:
Effects: return a short string for this ChemGraph. it includes two parts:
(1) the graph string without H
Modifies:
*/
//## operation toStringWithoutH()
public String toStringWithoutH(int i) {
//#[ operation toStringWithoutH()
String s = "";//= "ChemFormula: " + getChemicalFormula() + '\n';
if (getHeavyAtomNumber() == 0)
s += getGraph().toStringWithoutCentralID();
else
s = s + getGraph().toStringWithoutCentralIDAndH();
return s;
//#]
}
/**
Requires:
Effects: check all the atom to see if it satisfies:
Val of atom = radical number + ion number + sum of bond orders.
if it is satisfied, return true, otherwise return false.
Modifies:
*/
//## operation valencyOk()
public boolean valencyOk() throws InvalidNodeElementException {
//#[ operation valencyOk()
Iterator node_iter = graph.getNodeList();
while (node_iter.hasNext()) {
Node node = (Node)node_iter.next();
Atom atom = (Atom)node.getElement();
double val = atom.getValency();
Iterator arc_iter = node.getNeighbor();
while (arc_iter.hasNext()) {
Bond bond = (Bond)((Arc)(arc_iter.next())).getElement();
val -= bond.getOrder();
}
if (Math.abs(val) >= 1e-10) return false;
}
return true;
//#]
}
public int getMAX_OXYGEN_NUM() {
return MAX_OXYGEN_NUM;
}
public static int getMAX_RADICAL_NUM() {
return MAX_RADICAL_NUM;
}
public static HashSet getForbiddenStructure() {
return forbiddenStructure;
}
public int getInternalRotor() {
if (internalRotor <0 ){
calculateInternalRotor();
}
return internalRotor;
}
/*public HashSet getSymmetryAxis() {
return symmetryAxis;
}*/
protected String getUniqueString() {
return uniqueString;
}
public Graph getGraph() {
return graph;
}
public void setGraph(Graph p_graph){
graph = p_graph;
}
public Species getSpecies() {
return species;
}
public void setSpecies(Species p_Species) {
species = p_Species;
}
public GeneralGAPP getThermoGAPP() {
return thermoGAPP;
}
public GeneralAbramGAPP getAbramGAPP() {
return abramGAPP;
}
public void setThermoGAPP(GeneralGAPP p_GeneralGAPP) {
thermoGAPP = p_GeneralGAPP;
}
public void setAbramGAPP(GeneralAbramGAPP p_GeneralAbramGAPP) {
abramGAPP = p_GeneralAbramGAPP;
}
public static void setMaxCarbonNumber(int maxCNumber) {
MAX_CARBON_NUM = maxCNumber;
}
public static void setMaxOxygenNumber(int maxONumber) {
MAX_OXYGEN_NUM = maxONumber;
}
public static void setMaxRadicalNumber(int maxRadNumber) {
MAX_RADICAL_NUM = maxRadNumber;
}
public static void setMaxSulfurNumber(int maxSNumber) {
MAX_SULFUR_NUM = maxSNumber;
}
public static void setMaxSiliconNumber(int maxSiNumber) {
MAX_SILICON_NUM = maxSiNumber;
}
public static void setMaxHeavyAtomNumber(int maxHANumber) {
MAX_HEAVYATOM_NUM = maxHANumber;
}
public static void setMaxCycleNumber(int maxCycleNumber) {
MAX_CYCLE_NUM = maxCycleNumber;
}
public int getHeavyAtomNumber() {
return getCarbonNumber() + getOxygenNumber() + getSulfurNumber() + getSiliconNumber();
}
public void setRepOkString(String s) {
repOkString = s;
}
public static String getRepOkString() {
return repOkString;
}
public void appendThermoComments(String newComment) {
thermoComments += newComment + "\t";
}
public String getThermoComments() {
return thermoComments;
}
public void appendFreqComments(String newComment) {
freqComments += newComment + "\t";
}
public String getFreqComments() {
return freqComments;
}
}
/*********************************************************************
File Path : RMG\RMG\jing\chem\ChemGraph.java
*********************************************************************/
| bug fix for aromatics perception: implicit hydrogens
in case one does not define the explicit hydrogens in an adjacency
list, the aromatics perception algo wrongly calculates the
'used_valency' counter.
Now, the addMissingHydrogen() method is called at the beginning
of the algorithm to make sure all hydrogens are explicit.
This bug was found by the case of the five membered ring species
(InChI=1S/C5H5/c1-2-4-5-3-1/h1-2,5H,3H2) containing an sp3 hybridized
carbon without explicit hydrogens. Because this carbon only had
two as the value of used_valency, it contributed two to the pi-electron
count, turning this non-aromatic species into an aromatic one.
Again, the Cs atom would turn into an Cb atom and only one explicit
hydrogen would be added instead of two. So here the aromatics perception
algorithm wrongly removes a hydrogen instead of wrongly adding one
for Cdd or Ct atoms.
| source/RMG/jing/chem/ChemGraph.java | bug fix for aromatics perception: implicit hydrogens |
|
Java | epl-1.0 | 94718c4fe87ce3f316175d094d2f29af6a872aa5 | 0 | test-editor/test-editor,test-editor/test-editor,test-editor/test-editor,test-editor/test-editor | /*******************************************************************************
* Copyright (c) 2012 - 2015 Signal Iduna Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Signal Iduna Corporation - initial API and implementation
* akquinet AG
*******************************************************************************/
package org.testeditor.ui.handlers;
import java.lang.reflect.InvocationTargetException;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.eclipse.e4.core.contexts.Active;
import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.annotations.CanExecute;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.testeditor.core.model.testresult.TestResult;
import org.testeditor.core.model.teststructure.TestStructure;
import org.testeditor.core.model.teststructure.TestSuite;
import org.testeditor.core.services.interfaces.TestEditorPlugInService;
import org.testeditor.core.services.interfaces.TestStructureService;
import org.testeditor.core.util.TestProtocolService;
import org.testeditor.ui.constants.TestEditorConstants;
import org.testeditor.ui.constants.TestEditorUIEventConstants;
import org.testeditor.ui.parts.testExplorer.TestExplorer;
import org.testeditor.ui.reporting.TestExecutionProgressDialog;
import org.testeditor.ui.utilities.TestEditorTranslationService;
/**
* Run Tests on a <code>TestStructure</code> (<code>TestCase</code> or
* <code>TestSuite</code>).
*
*/
public class RunTestHandler {
private static final Logger LOGGER = Logger.getLogger(RunTestHandler.class);
@Inject
private static TestEditorTranslationService translationService;
@Inject
private TestEditorPlugInService testEditorPluginService;
private TestResult testResult;
/**
* Check if this handler is enabled. It is only enabled on
* <code>TestStructures</code> which contain tests. It is only enabled on
* One Element. Enable is possible with an open Editor View or a selection
* in the TestExplorer.
*
* @param partService
* of the active window.
*
* @return true if only one <code>TestStructure</code> is selected.
*/
@CanExecute
public boolean canExecute(EPartService partService) {
TestExplorer explorer = (TestExplorer) partService.findPart(TestEditorConstants.TEST_EXPLORER_VIEW).getObject();
CanExecuteTestExplorerHandlerRules canExecuteTestExplorerHandlerRules = new CanExecuteTestExplorerHandlerRules();
return canExecuteTestExplorerHandlerRules.canExecuteOnlyOneElementRule(explorer)
&& !canExecuteTestExplorerHandlerRules.canExecuteOnTestScenarioRule(explorer)
&& (((TestStructure) explorer.getSelection().getFirstElement()).isExecutableTestStructure());
}
/**
* @param shell
* Active Shell. Runs the selected <code>TestStructure</code>.
*
* @param protocolService
* to store the current execution state.
* @param context
* the active Eclipse Context
* @param eventBroker
* the eventBroker
* @param partService
* of the active window.
*/
@Execute
public void execute(@Active Shell shell, TestProtocolService protocolService, IEclipseContext context,
IEventBroker eventBroker, EPartService partService) {
TestExplorer testExplorer = (TestExplorer) partService.findPart(TestEditorConstants.TEST_EXPLORER_VIEW)
.getObject();
final TestStructure selectedTestStructure = (TestStructure) testExplorer.getSelection().getFirstElement();
try {
if (partService.saveAll(true)) {
LOGGER.info("Running Test: " + selectedTestStructure);
final TestStructureService testStructureService = testEditorPluginService
.getTestStructureServiceFor(selectedTestStructure.getRootElement().getTestProjectConfig()
.getTestServerID());
context.set("ActualTCService", testStructureService);
TestExecutionProgressDialog dlg = ContextInjectionFactory.make(TestExecutionProgressDialog.class,
context);
testResult = dlg.executeTest(selectedTestStructure);
// refresh the icon depends on test result
protocolService.set(selectedTestStructure, testResult);
refreshTestStructureInTree(selectedTestStructure, testExplorer);
// refresh refferredTestCaseViewer
eventBroker.send(TestEditorUIEventConstants.TESTSTRUCTURE_EXECUTED, selectedTestStructure);
}
} catch (InvocationTargetException e) {
MessageDialog.openError(Display.getCurrent().getActiveShell(), "System-Exception", e.getTargetException()
.getLocalizedMessage());
} catch (InterruptedException e) {
MessageDialog.openInformation(Display.getCurrent().getActiveShell(),
translationService.translate("%TestInterruptedByUserTitle"),
translationService.translate("%TestInterruptedByUserMessage"));
}
}
/**
* refreshes the item in the treeviewer of selected TestStructure and, if
* the selected TestStructure is a TestScenario, also the children.
*
* @param testStructure
* the TestStructure of the Item in the TreeViewer to refresh
* @param testExplorer
* the TestExplorer with the tree
*/
private void refreshTestStructureInTree(TestStructure testStructure, TestExplorer testExplorer) {
if (testStructure instanceof TestSuite) {
for (TestStructure ts : ((TestSuite) testStructure).getAllTestChildrensAndReferedTestcases()) {
refreshTestStructureInTree(ts, testExplorer);
}
}
testExplorer.refreshTreeViewerOnTestStrucutre(testStructure);
}
}
| ui/org.testeditor.ui/src/org/testeditor/ui/handlers/RunTestHandler.java | /*******************************************************************************
* Copyright (c) 2012 - 2015 Signal Iduna Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Signal Iduna Corporation - initial API and implementation
* akquinet AG
*******************************************************************************/
package org.testeditor.ui.handlers;
import java.lang.reflect.InvocationTargetException;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.eclipse.e4.core.contexts.Active;
import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.annotations.CanExecute;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.testeditor.core.model.testresult.TestResult;
import org.testeditor.core.model.teststructure.TestStructure;
import org.testeditor.core.model.teststructure.TestSuite;
import org.testeditor.core.services.interfaces.TestEditorPlugInService;
import org.testeditor.core.services.interfaces.TestStructureService;
import org.testeditor.core.util.TestProtocolService;
import org.testeditor.ui.constants.TestEditorConstants;
import org.testeditor.ui.constants.TestEditorEventConstants;
import org.testeditor.ui.constants.TestEditorUIEventConstants;
import org.testeditor.ui.parts.testExplorer.TestExplorer;
import org.testeditor.ui.reporting.TestExecutionProgressDialog;
import org.testeditor.ui.utilities.TestEditorTranslationService;
/**
* Run Tests on a <code>TestStructure</code> (<code>TestCase</code> or
* <code>TestSuite</code>).
*
*/
public class RunTestHandler {
private static final Logger LOGGER = Logger.getLogger(RunTestHandler.class);
@Inject
private static TestEditorTranslationService translationService;
@Inject
private TestEditorPlugInService testEditorPluginService;
private TestResult testResult;
/**
* Check if this handler is enabled. It is only enabled on
* <code>TestStructures</code> which contain tests. It is only enabled on
* One Element. Enable is possible with an open Editor View or a selection
* in the TestExplorer.
*
* @param partService
* of the active window.
*
* @return true if only one <code>TestStructure</code> is selected.
*/
@CanExecute
public boolean canExecute(EPartService partService) {
TestExplorer explorer = (TestExplorer) partService.findPart(TestEditorConstants.TEST_EXPLORER_VIEW).getObject();
CanExecuteTestExplorerHandlerRules canExecuteTestExplorerHandlerRules = new CanExecuteTestExplorerHandlerRules();
return canExecuteTestExplorerHandlerRules.canExecuteOnlyOneElementRule(explorer)
&& !canExecuteTestExplorerHandlerRules.canExecuteOnTestScenarioRule(explorer)
&& (((TestStructure) explorer.getSelection().getFirstElement()).isExecutableTestStructure());
}
/**
* @param shell
* Active Shell. Runs the selected <code>TestStructure</code>.
*
* @param protocolService
* to store the current execution state.
* @param context
* the active Eclipse Context
* @param eventBroker
* the eventBroker
* @param partService
* of the active window.
*/
@Execute
public void execute(@Active Shell shell, TestProtocolService protocolService, IEclipseContext context,
IEventBroker eventBroker, EPartService partService) {
TestExplorer testExplorer = (TestExplorer) partService.findPart(TestEditorConstants.TEST_EXPLORER_VIEW)
.getObject();
final TestStructure selectedTestStructure = (TestStructure) testExplorer.getSelection().getFirstElement();
try {
partService.saveAll(true);
LOGGER.info("Running Test: " + selectedTestStructure);
final TestStructureService testStructureService = testEditorPluginService
.getTestStructureServiceFor(selectedTestStructure.getRootElement().getTestProjectConfig()
.getTestServerID());
context.set("ActualTCService", testStructureService);
TestExecutionProgressDialog dlg = ContextInjectionFactory.make(TestExecutionProgressDialog.class, context);
testResult = dlg.executeTest(selectedTestStructure);
// refresh the icon depends on test result
protocolService.set(selectedTestStructure, testResult);
refreshTestStructureInTree(selectedTestStructure, testExplorer);
// refresh refferredTestCaseViewer
eventBroker.send(TestEditorUIEventConstants.TESTSTRUCTURE_EXECUTED, selectedTestStructure);
} catch (InvocationTargetException e) {
MessageDialog.openError(Display.getCurrent().getActiveShell(), "System-Exception", e.getTargetException()
.getLocalizedMessage());
} catch (InterruptedException e) {
MessageDialog.openInformation(Display.getCurrent().getActiveShell(),
translationService.translate("%TestInterruptedByUserTitle"),
translationService.translate("%TestInterruptedByUserMessage"));
}
}
/**
* refreshes the item in the treeviewer of selected TestStructure and, if
* the selected TestStructure is a TestScenario, also the children.
*
* @param testStructure
* the TestStructure of the Item in the TreeViewer to refresh
* @param testExplorer
* the TestExplorer with the tree
*/
private void refreshTestStructureInTree(TestStructure testStructure, TestExplorer testExplorer) {
if (testStructure instanceof TestSuite) {
for (TestStructure ts : ((TestSuite) testStructure).getAllTestChildrensAndReferedTestcases()) {
refreshTestStructureInTree(ts, testExplorer);
}
}
testExplorer.refreshTreeViewerOnTestStrucutre(testStructure);
}
}
| [TE-80] Check Button selection on saveall dialog. | ui/org.testeditor.ui/src/org/testeditor/ui/handlers/RunTestHandler.java | [TE-80] Check Button selection on saveall dialog. |
|
Java | mpl-2.0 | a968501dc487a0e7b77d74e5bffcdd4295b63dca | 0 | AbhijitParate/openmrs-core,shiangree/openmrs-core,alexei-grigoriev/openmrs-core,foolchan2556/openmrs-core,lilo2k/openmrs-core,dcmul/openmrs-core,asifur77/openmrs,lilo2k/openmrs-core,kristopherschmidt/openmrs-core,jcantu1988/openmrs-core,lbl52001/openmrs-core,sadhanvejella/openmrs,kckc/openmrs-core,lbl52001/openmrs-core,WANeves/openmrs-core,pselle/openmrs-core,jamesfeshner/openmrs-module,donaldgavis/openmrs-core,sravanthi17/openmrs-core,foolchan2556/openmrs-core,chethandeshpande/openmrs-core,shiangree/openmrs-core,jembi/openmrs-core,aj-jaswanth/openmrs-core,kigsmtua/openmrs-core,trsorsimoII/openmrs-core,jembi/openmrs-core,prisamuel/openmrs-core,milankarunarathne/openmrs-core,andyvand/OpenMRS,andyvand/OpenMRS,macorrales/openmrs-core,asifur77/openmrs,milankarunarathne/openmrs-core,nilusi/Legacy-UI,rbtracker/openmrs-core,jvena1/openmrs-core,sravanthi17/openmrs-core,WANeves/openmrs-core,sadhanvejella/openmrs,sintjuri/openmrs-core,AbhijitParate/openmrs-core,pselle/openmrs-core,aj-jaswanth/openmrs-core,jamesfeshner/openmrs-module,kckc/openmrs-core,preethi29/openmrs-core,AbhijitParate/openmrs-core,vinayvenu/openmrs-core,shiangree/openmrs-core,MuhammadSafwan/Stop-Button-Ability,michaelhofer/openmrs-core,AbhijitParate/openmrs-core,spereverziev/openmrs-core,aboutdata/openmrs-core,sadhanvejella/openmrs,ssmusoke/openmrs-core,sravanthi17/openmrs-core,lilo2k/openmrs-core,donaldgavis/openmrs-core,siddharthkhabia/openmrs-core,rbtracker/openmrs-core,hoquangtruong/TestMylyn,milankarunarathne/openmrs-core,Winbobob/openmrs-core,ern2/openmrs-core,donaldgavis/openmrs-core,lbl52001/openmrs-core,chethandeshpande/openmrs-core,siddharthkhabia/openmrs-core,Winbobob/openmrs-core,donaldgavis/openmrs-core,michaelhofer/openmrs-core,shiangree/openmrs-core,aj-jaswanth/openmrs-core,jembi/openmrs-core,prisamuel/openmrs-core,jcantu1988/openmrs-core,kabariyamilind/openMRSDEV,MuhammadSafwan/Stop-Button-Ability,kckc/openmrs-core,kristopherschmidt/openmrs-core,prisamuel/openmrs-core,joansmith/openmrs-core,pselle/openmrs-core,aboutdata/openmrs-core,sintjuri/openmrs-core,dcmul/openmrs-core,vinayvenu/openmrs-core,siddharthkhabia/openmrs-core,dlahn/openmrs-core,ern2/openmrs-core,ern2/openmrs-core,vinayvenu/openmrs-core,MitchellBot/openmrs-core,koskedk/openmrs-core,AbhijitParate/openmrs-core,ldf92/openmrs-core,maany/openmrs-core,ldf92/openmrs-core,iLoop2/openmrs-core,WANeves/openmrs-core,pselle/openmrs-core,kigsmtua/openmrs-core,ssmusoke/openmrs-core,maekstr/openmrs-core,foolchan2556/openmrs-core,alexwind26/openmrs-core,chethandeshpande/openmrs-core,ldf92/openmrs-core,spereverziev/openmrs-core,dlahn/openmrs-core,koskedk/openmrs-core,aj-jaswanth/openmrs-core,foolchan2556/openmrs-core,Negatu/openmrs-core,maany/openmrs-core,WANeves/openmrs-core,jvena1/openmrs-core,maany/openmrs-core,trsorsimoII/openmrs-core,maekstr/openmrs-core,alexwind26/openmrs-core,kristopherschmidt/openmrs-core,sintjuri/openmrs-core,lilo2k/openmrs-core,alexei-grigoriev/openmrs-core,ssmusoke/openmrs-core,macorrales/openmrs-core,Openmrs-joel/openmrs-core,asifur77/openmrs,koskedk/openmrs-core,spereverziev/openmrs-core,alexwind26/openmrs-core,shiangree/openmrs-core,MuhammadSafwan/Stop-Button-Ability,alexei-grigoriev/openmrs-core,maany/openmrs-core,trsorsimoII/openmrs-core,geoff-wasilwa/openmrs-core,rbtracker/openmrs-core,rbtracker/openmrs-core,koskedk/openmrs-core,sintjuri/openmrs-core,aboutdata/openmrs-core,Openmrs-joel/openmrs-core,nilusi/Legacy-UI,joansmith/openmrs-core,prisamuel/openmrs-core,chethandeshpande/openmrs-core,lbl52001/openmrs-core,sadhanvejella/openmrs,Negatu/openmrs-core,jcantu1988/openmrs-core,kckc/openmrs-core,kristopherschmidt/openmrs-core,pselle/openmrs-core,vinayvenu/openmrs-core,nilusi/Legacy-UI,jvena1/openmrs-core,dlahn/openmrs-core,jvena1/openmrs-core,dcmul/openmrs-core,preethi29/openmrs-core,lbl52001/openmrs-core,maekstr/openmrs-core,maekstr/openmrs-core,sintjuri/openmrs-core,Negatu/openmrs-core,asifur77/openmrs,ssmusoke/openmrs-core,naraink/openmrs-core,Ch3ck/openmrs-core,Winbobob/openmrs-core,naraink/openmrs-core,Ch3ck/openmrs-core,dcmul/openmrs-core,Openmrs-joel/openmrs-core,kckc/openmrs-core,naraink/openmrs-core,siddharthkhabia/openmrs-core,jembi/openmrs-core,jamesfeshner/openmrs-module,hoquangtruong/TestMylyn,sadhanvejella/openmrs,joansmith/openmrs-core,maany/openmrs-core,ern2/openmrs-core,MitchellBot/openmrs-core,alexei-grigoriev/openmrs-core,maekstr/openmrs-core,alexei-grigoriev/openmrs-core,lbl52001/openmrs-core,macorrales/openmrs-core,iLoop2/openmrs-core,hoquangtruong/TestMylyn,koskedk/openmrs-core,nilusi/Legacy-UI,geoff-wasilwa/openmrs-core,michaelhofer/openmrs-core,Winbobob/openmrs-core,kckc/openmrs-core,joansmith/openmrs-core,lilo2k/openmrs-core,andyvand/OpenMRS,kigsmtua/openmrs-core,kristopherschmidt/openmrs-core,andyvand/OpenMRS,preethi29/openmrs-core,kabariyamilind/openMRSDEV,michaelhofer/openmrs-core,geoff-wasilwa/openmrs-core,joansmith/openmrs-core,iLoop2/openmrs-core,geoff-wasilwa/openmrs-core,asifur77/openmrs,lilo2k/openmrs-core,Openmrs-joel/openmrs-core,hoquangtruong/TestMylyn,AbhijitParate/openmrs-core,donaldgavis/openmrs-core,sintjuri/openmrs-core,dcmul/openmrs-core,dlahn/openmrs-core,geoff-wasilwa/openmrs-core,maekstr/openmrs-core,dlahn/openmrs-core,siddharthkhabia/openmrs-core,jcantu1988/openmrs-core,kabariyamilind/openMRSDEV,spereverziev/openmrs-core,kigsmtua/openmrs-core,koskedk/openmrs-core,sravanthi17/openmrs-core,MitchellBot/openmrs-core,MitchellBot/openmrs-core,milankarunarathne/openmrs-core,Winbobob/openmrs-core,alexwind26/openmrs-core,jvena1/openmrs-core,macorrales/openmrs-core,MuhammadSafwan/Stop-Button-Ability,MuhammadSafwan/Stop-Button-Ability,nilusi/Legacy-UI,aboutdata/openmrs-core,MuhammadSafwan/Stop-Button-Ability,vinayvenu/openmrs-core,milankarunarathne/openmrs-core,Ch3ck/openmrs-core,Openmrs-joel/openmrs-core,nilusi/Legacy-UI,jamesfeshner/openmrs-module,kabariyamilind/openMRSDEV,kigsmtua/openmrs-core,prisamuel/openmrs-core,andyvand/OpenMRS,Ch3ck/openmrs-core,spereverziev/openmrs-core,prisamuel/openmrs-core,iLoop2/openmrs-core,michaelhofer/openmrs-core,naraink/openmrs-core,kabariyamilind/openMRSDEV,foolchan2556/openmrs-core,siddharthkhabia/openmrs-core,chethandeshpande/openmrs-core,Negatu/openmrs-core,kigsmtua/openmrs-core,iLoop2/openmrs-core,sadhanvejella/openmrs,WANeves/openmrs-core,aboutdata/openmrs-core,jcantu1988/openmrs-core,aj-jaswanth/openmrs-core,macorrales/openmrs-core,shiangree/openmrs-core,dcmul/openmrs-core,Winbobob/openmrs-core,iLoop2/openmrs-core,andyvand/OpenMRS,foolchan2556/openmrs-core,hoquangtruong/TestMylyn,aboutdata/openmrs-core,WANeves/openmrs-core,trsorsimoII/openmrs-core,trsorsimoII/openmrs-core,preethi29/openmrs-core,pselle/openmrs-core,jamesfeshner/openmrs-module,spereverziev/openmrs-core,Negatu/openmrs-core,rbtracker/openmrs-core,naraink/openmrs-core,ldf92/openmrs-core,hoquangtruong/TestMylyn,alexwind26/openmrs-core,jembi/openmrs-core,jembi/openmrs-core,Negatu/openmrs-core,MitchellBot/openmrs-core,Ch3ck/openmrs-core,preethi29/openmrs-core,alexei-grigoriev/openmrs-core,milankarunarathne/openmrs-core,ldf92/openmrs-core,ssmusoke/openmrs-core,ern2/openmrs-core,sravanthi17/openmrs-core,naraink/openmrs-core | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.api.context;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aopalliance.aop.Advice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.api.APIException;
import org.openmrs.api.ActiveListService;
import org.openmrs.api.AdministrationService;
import org.openmrs.api.CohortService;
import org.openmrs.api.ConceptService;
import org.openmrs.api.DataSetService;
import org.openmrs.api.EncounterService;
import org.openmrs.api.FormService;
import org.openmrs.api.LocationService;
import org.openmrs.api.ObsService;
import org.openmrs.api.OrderService;
import org.openmrs.api.PatientService;
import org.openmrs.api.PatientSetService;
import org.openmrs.api.PersonService;
import org.openmrs.api.ProgramWorkflowService;
import org.openmrs.api.ReportService;
import org.openmrs.api.SerializationService;
import org.openmrs.api.UserService;
import org.openmrs.arden.ArdenService;
import org.openmrs.hl7.HL7Service;
import org.openmrs.logic.LogicService;
import org.openmrs.messagesource.MessageSourceService;
import org.openmrs.notification.AlertService;
import org.openmrs.notification.MessageService;
import org.openmrs.reporting.ReportObjectService;
import org.openmrs.scheduler.SchedulerService;
import org.openmrs.util.OpenmrsClassLoader;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Represents an OpenMRS <code>Service Context</code>, which returns the services represented
* throughout the system. <br/>
* <br/>
* This class should not be access directly, but rather used through the <code>Context</code> class. <br/>
* <br/>
* This class is essentially static and only one instance is kept because this is fairly
* heavy-weight. Spring takes care of filling in the actual service implementations via dependency
* injection. See the /metadata/api/spring/applicationContext-service.xml file. <br/>
* <br/>
* Module services are also accessed through this class. See {@link #getService(Class)}
*
* @see org.openmrs.api.context.Context
*/
public class ServiceContext implements ApplicationContextAware {
private static final Log log = LogFactory.getLog(ServiceContext.class);
private static ServiceContext instance;
private ApplicationContext applicationContext;
private Boolean refreshingContext = new Boolean(false);
/**
* Static variable holding whether or not to use the system classloader. By default this is
* false so the openmrs classloader is used instead
*/
private boolean useSystemClassLoader = false;
// Cached service objects
@SuppressWarnings("unchecked")
Map<Class, Object> services = new HashMap<Class, Object>();
// Advisors added to services by this service
@SuppressWarnings("unchecked")
Map<Class, Set<Advisor>> addedAdvisors = new HashMap<Class, Set<Advisor>>();
// Advice added to services by this service
@SuppressWarnings("unchecked")
Map<Class, Set<Advice>> addedAdvice = new HashMap<Class, Set<Advice>>();
/**
* The default constructor is private so as to keep only one instance per java vm.
*
* @see ServiceContext#getInstance()
*/
private ServiceContext() {
log.debug("Instantiating service context");
}
/**
* There should only be one ServiceContext per openmrs (java virtual machine). This method
* should be used when wanting to fetch the service context Note: The ServiceContext shouldn't
* be used independently. All calls should go through the Context
*
* @return This VM's current ServiceContext.
* @see org.openmrs.api.context.Context
*/
public static ServiceContext getInstance() {
if (instance == null)
instance = new ServiceContext();
return instance;
}
/**
* Null out the current instance of the ServiceContext. This should be used when modules are
* refreshing (being added/removed) and/or openmrs is shutting down
*/
@SuppressWarnings("unchecked")
public static void destroyInstance() {
if (instance != null && instance.services != null) {
if (log.isDebugEnabled()) {
for (Map.Entry<Class, Object> entry : instance.services.entrySet()) {
log.debug("Service - " + entry.getKey().getName() + ":" + entry.getValue());
}
}
// Remove advice and advisors that this service added
for (Class serviceClass : instance.services.keySet()) {
instance.removeAddedAOP(serviceClass);
}
if (instance.services != null) {
instance.services.clear();
instance.services = null;
}
if (instance.addedAdvisors != null) {
instance.addedAdvisors.clear();
instance.addedAdvisors = null;
}
if (instance.addedAdvice != null) {
instance.addedAdvice.clear();
instance.addedAdvice = null;
}
}
if (log.isDebugEnabled())
log.debug("Destroying ServiceContext instance: " + instance);
instance = null;
}
/**
* @return encounter-related services
*/
public EncounterService getEncounterService() {
return getService(EncounterService.class);
}
/**
* @return location services
*/
public LocationService getLocationService() {
return getService(LocationService.class);
}
/**
* @return observation services
*/
public ObsService getObsService() {
return getService(ObsService.class);
}
/**
* @return patientset-related services
*/
public PatientSetService getPatientSetService() {
return getService(PatientSetService.class);
}
/**
* @return cohort related service
*/
public CohortService getCohortService() {
return getService(CohortService.class);
}
/**
* @param cs cohort related service
*/
public void setCohortService(CohortService cs) {
setService(CohortService.class, cs);
}
/**
* @return order service
*/
public OrderService getOrderService() {
return getService(OrderService.class);
}
/**
* @return form service
*/
public FormService getFormService() {
return getService(FormService.class);
}
/**
* @return report object service
* @deprecated see reportingcompatibility module
*/
@Deprecated
public ReportObjectService getReportObjectService() {
return getService(ReportObjectService.class);
}
/**
* @return serialization service
*/
public SerializationService getSerializationService() {
return getService(SerializationService.class);
}
/**
* @return report service
* @deprecated see reportingcompatibility module
*/
@Deprecated
public ReportService getReportService() {
return getService(ReportService.class);
}
/**
* @return admin-related services
*/
public AdministrationService getAdministrationService() {
return getService(AdministrationService.class);
}
/**
* @return programWorkflowService
*/
public ProgramWorkflowService getProgramWorkflowService() {
return getService(ProgramWorkflowService.class);
}
/**
* @return ardenService
*/
public ArdenService getArdenService() {
return getService(ArdenService.class);
}
/**
* @return logicService
*/
public LogicService getLogicService() {
return getService(LogicService.class);
}
/**
* @return scheduler service
*/
public SchedulerService getSchedulerService() {
return getService(SchedulerService.class);
}
/**
* Set the scheduler service.
*
* @param schedulerService
*/
public void setSchedulerService(SchedulerService schedulerService) {
setService(SchedulerService.class, schedulerService);
}
/**
* @return alert service
*/
public AlertService getAlertService() {
return getService(AlertService.class);
}
/**
* @param alertService
*/
public void setAlertService(AlertService alertService) {
setService(AlertService.class, alertService);
}
/**
* @param programWorkflowService
*/
public void setProgramWorkflowService(ProgramWorkflowService programWorkflowService) {
setService(ProgramWorkflowService.class, programWorkflowService);
}
/**
* @param ardenService
*/
public void setArdenService(ArdenService ardenService) {
setService(ArdenService.class, ardenService);
}
/**
* @param logicService
*/
public void setLogicService(LogicService logicService) {
setService(LogicService.class, logicService);
}
/**
* @return message service
*/
public MessageService getMessageService() {
return getService(MessageService.class);
}
/**
* Sets the message service.
*
* @param messageService
*/
public void setMessageService(MessageService messageService) {
setService(MessageService.class, messageService);
}
/**
* @return the hl7Service
*/
public HL7Service getHL7Service() {
return getService(HL7Service.class);
}
/**
* @param hl7Service the hl7Service to set
*/
// TODO spring is demanding that this be hl7Service:setHl7Service and not hL7Service:setHL7Service. why?
public void setHl7Service(HL7Service hl7Service) {
setService(HL7Service.class, hl7Service);
}
/**
* @param administrationService the administrationService to set
*/
public void setAdministrationService(AdministrationService administrationService) {
setService(AdministrationService.class, administrationService);
}
/**
* @param encounterService the encounterService to set
*/
public void setEncounterService(EncounterService encounterService) {
setService(EncounterService.class, encounterService);
}
/**
* @param locationService the LocationService to set
*/
public void setLocationService(LocationService locationService) {
setService(LocationService.class, locationService);
}
/**
* @param formService the formService to set
*/
public void setFormService(FormService formService) {
setService(FormService.class, formService);
}
/**
* @param obsService the obsService to set
*/
public void setObsService(ObsService obsService) {
setService(ObsService.class, obsService);
}
/**
* @param orderService the orderService to set
*/
public void setOrderService(OrderService orderService) {
setService(OrderService.class, orderService);
}
/**
* @param patientSetService the patientSetService to set
*/
public void setPatientSetService(PatientSetService patientSetService) {
setService(PatientSetService.class, patientSetService);
}
/**
* @param reportObjectService the reportObjectService to set
* @deprecated see reportingcompatibility module
*/
@Deprecated
public void setReportObjectService(ReportObjectService reportObjectService) {
setService(ReportObjectService.class, reportObjectService);
}
/**
* @param reportService
* @deprecated see reportingcompatibility module
*/
@Deprecated
public void setReportService(ReportService reportService) {
setService(ReportService.class, reportService);
}
/**
* @param serializationService
*/
public void setSerializationService(SerializationService serializationService) {
setService(SerializationService.class, serializationService);
}
/**
* @param dataSetService
* @deprecated see reportingcompatibility module
*/
@Deprecated
public void setDataSetService(DataSetService dataSetService) {
setService(DataSetService.class, dataSetService);
}
/**
* @return the DataSetService
* @deprecated see reportingcompatibility module
*/
@Deprecated
public DataSetService getDataSetService() {
return getService(DataSetService.class);
}
/**
* @return patient related services
*/
public PatientService getPatientService() {
return getService(PatientService.class);
}
/**
* @param patientService the patientService to set
*/
public void setPatientService(PatientService patientService) {
setService(PatientService.class, patientService);
}
/**
* @return person related services
*/
public PersonService getPersonService() {
return getService(PersonService.class);
}
/**
* @param personService the personService to set
*/
public void setPersonService(PersonService personService) {
setService(PersonService.class, personService);
}
/**
* @return concept related services
*/
public ConceptService getConceptService() {
return getService(ConceptService.class);
}
/**
* @param conceptService the conceptService to set
*/
public void setConceptService(ConceptService conceptService) {
setService(ConceptService.class, conceptService);
}
/**
* @return user-related services
*/
public UserService getUserService() {
return getService(UserService.class);
}
/**
* @param userService the userService to set
*/
public void setUserService(UserService userService) {
setService(UserService.class, userService);
}
/**
* Gets the MessageSourceService used in the context.
*
* @return MessageSourceService
*/
public MessageSourceService getMessageSourceService() {
return getService(MessageSourceService.class);
}
/**
* Sets the MessageSourceService used in the context.
*
* @param messageSourceService the MessageSourceService to use
*/
public void setMessageSourceService(MessageSourceService messageSourceService) {
setService(MessageSourceService.class, messageSourceService);
}
/**
* Gets the ActiveListService used in the context.
*
* @return ActiveListService
*/
public ActiveListService getActiveListService() {
return getService(ActiveListService.class);
}
/**
* Sets the ActiveListService used in the context
*/
public void setActiveListService(ActiveListService activeListService) {
setService(ActiveListService.class, activeListService);
}
/**
* @param cls
* @param advisor
*/
@SuppressWarnings("unchecked")
public void addAdvisor(Class cls, Advisor advisor) {
Advised advisedService = (Advised) services.get(cls);
if (advisedService.indexOf(advisor) < 0)
advisedService.addAdvisor(advisor);
if (addedAdvisors.get(cls) == null)
addedAdvisors.put(cls, new HashSet<Advisor>());
getAddedAdvisors(cls).add(advisor);
}
/**
* @param cls
* @param advice
*/
@SuppressWarnings("unchecked")
public void addAdvice(Class cls, Advice advice) {
Advised advisedService = (Advised) services.get(cls);
if (advisedService.indexOf(advice) < 0)
advisedService.addAdvice(advice);
if (addedAdvice.get(cls) == null)
addedAdvice.put(cls, new HashSet<Advice>());
getAddedAdvice(cls).add(advice);
}
/**
* @param cls
* @param advisor
*/
@SuppressWarnings("unchecked")
public void removeAdvisor(Class cls, Advisor advisor) {
Advised advisedService = (Advised) services.get(cls);
advisedService.removeAdvisor(advisor);
getAddedAdvisors(cls).remove(advisor);
}
/**
* @param cls
* @param advice
*/
@SuppressWarnings("unchecked")
public void removeAdvice(Class cls, Advice advice) {
Advised advisedService = (Advised) services.get(cls);
advisedService.removeAdvice(advice);
getAddedAdvice(cls).remove(advice);
}
/**
* Moves advisors and advice added by ServiceContext from the source service to the target one.
*
* @param source the existing service
* @param target the new service
*/
@SuppressWarnings("unchecked")
private void moveAddedAOP(Advised source, Advised target) {
Class serviceClass = source.getClass();
Set<Advisor> existingAdvisors = getAddedAdvisors(serviceClass);
for (Advisor advisor : existingAdvisors) {
target.addAdvisor(advisor);
source.removeAdvisor(advisor);
}
Set<Advice> existingAdvice = getAddedAdvice(serviceClass);
for (Advice advice : existingAdvice) {
target.addAdvice(advice);
source.removeAdvice(advice);
}
}
/**
* Removes all advice and advisors added by ServiceContext.
*
* @param cls the class of the cached service to cleanup
*/
@SuppressWarnings("unchecked")
private void removeAddedAOP(Class cls) {
removeAddedAdvisors(cls);
removeAddedAdvice(cls);
}
/**
* Removes all the advisors added by ServiceContext.
*
* @param cls the class of the cached service to cleanup
*/
@SuppressWarnings("unchecked")
private void removeAddedAdvisors(Class cls) {
Advised advisedService = (Advised) services.get(cls);
Set<Advisor> advisorsToRemove = addedAdvisors.get(cls);
if (advisedService != null && advisorsToRemove != null) {
for (Advisor advisor : advisorsToRemove.toArray(new Advisor[] {}))
removeAdvisor(cls, advisor);
}
}
/**
* Returns the set of advisors added by ServiceContext.
*
* @param cls the class of the cached service
* @return the set of advisors or an empty set
*/
@SuppressWarnings("unchecked")
private Set<Advisor> getAddedAdvisors(Class cls) {
Set<Advisor> result = addedAdvisors.get(cls);
return result == null ? Collections.EMPTY_SET : result;
}
/**
* Removes all the advice added by the ServiceContext.
*
* @param cls the class of the caches service to cleanup
*/
@SuppressWarnings("unchecked")
private void removeAddedAdvice(Class cls) {
Advised advisedService = (Advised) services.get(cls);
Set<Advice> adviceToRemove = addedAdvice.get(cls);
if (advisedService != null && adviceToRemove != null) {
for (Advice advice : adviceToRemove.toArray(new Advice[] {}))
removeAdvice(cls, advice);
}
}
/**
* Returns the set of advice added by ServiceContext.
*
* @param cls the class of the cached service
* @return the set of advice or an empty set
*/
@SuppressWarnings("unchecked")
private Set<Advice> getAddedAdvice(Class cls) {
Set<Advice> result = addedAdvice.get(cls);
return result == null ? Collections.EMPTY_SET : result;
}
/**
* Returns the current proxy that is stored for the Class <code>cls</code>
*
* @param cls
* @return Object that is a proxy for the <code>cls</code> class
*/
@SuppressWarnings("unchecked")
public <T extends Object> T getService(Class<? extends T> cls) {
if (log.isTraceEnabled())
log.trace("Getting service: " + cls);
// if the context is refreshing, wait until it is
// done -- otherwise a null service might be returned
synchronized (refreshingContext) {
if (refreshingContext.booleanValue())
try {
log.warn("Waiting to get service: " + cls + " while the context is being refreshed");
refreshingContext.wait();
log.warn("Finished waiting to get service " + cls + " while the context was being refreshed");
}
catch (InterruptedException e) {
log.warn("Refresh lock was interrupted", e);
}
}
Object service = services.get(cls);
if (service == null)
throw new APIException("Service not found: " + cls);
return (T) service;
}
/**
* Allow other services to be added to our service layer
*
* @param cls Interface to proxy
* @param classInstance the actual instance of the <code>cls</code> interface
*/
@SuppressWarnings("unchecked")
public void setService(Class cls, Object classInstance) {
log.debug("Setting service: " + cls);
if (cls != null && classInstance != null) {
try {
Advised cachedService = (Advised) services.get(cls);
boolean noExistingService = cachedService == null;
boolean replacingService = cachedService != null && cachedService != classInstance;
boolean serviceAdvised = classInstance instanceof Advised;
if (noExistingService || replacingService) {
Advised advisedService;
if (!serviceAdvised) {
// Adding a bare service, wrap with AOP proxy
Class[] interfaces = { cls };
ProxyFactory factory = new ProxyFactory(interfaces);
factory.setTarget(classInstance);
advisedService = (Advised) factory.getProxy(OpenmrsClassLoader.getInstance());
} else
advisedService = (Advised) classInstance;
if (replacingService)
moveAddedAOP(cachedService, advisedService);
services.put(cls, advisedService);
}
log.debug("Service: " + cls + " set successfully");
}
catch (Exception e) {
throw new APIException("Unable to create proxy factory for: " + classInstance.getClass().getName(), e);
}
}
}
/**
* Allow other services to be added to our service layer <br/>
* <br/>
* Classes will be found/loaded with the ModuleClassLoader <br/>
* <br/>
* <code>params</code>[0] = string representing the service interface<br/>
* <code>params</code>[1] = service instance
*
* @param params list of parameters
*/
@SuppressWarnings("unchecked")
public void setModuleService(List<Object> params) {
String classString = (String) params.get(0);
Object classInstance = params.get(1);
if (classString == null || classInstance == null) {
throw new APIException("Unable to find classString or classInstance in params");
}
Class cls = null;
// load the given 'classString' class from either the openmrs class
// loader or the system class loader depending on if we're in a testing
// environment or not (system == testing, openmrs == normal)
try {
if (useSystemClassLoader == false) {
cls = OpenmrsClassLoader.getInstance().loadClass(classString);
if (cls != null && log.isDebugEnabled()) {
try {
log.debug("cls classloader: " + cls.getClass().getClassLoader() + " uid: "
+ cls.getClass().getClassLoader().hashCode());
}
catch (Exception e) { /*pass*/}
}
} else if (useSystemClassLoader == true) {
try {
cls = Class.forName(classString);
if (log.isDebugEnabled()) {
log.debug("cls2 classloader: " + cls.getClass().getClassLoader() + " uid: "
+ cls.getClass().getClassLoader().hashCode());
log.debug("cls==cls2: " + String.valueOf(cls == cls));
}
}
catch (Exception e) { /*pass*/}
}
}
catch (ClassNotFoundException e) {
throw new APIException("Unable to set module service: " + classString, e);
}
// add this module service to the normal list of services
setService(cls, classInstance);
}
/**
* Set this service context to use the system class loader if the
* <code>useSystemClassLoader</code> is set to true. If false, the openmrs class loader is used
* to load module services
*
* @param useSystemClassLoader true/false whether to use the system class loader
*/
public void setUseSystemClassLoader(boolean useSystemClassLoader) {
this.useSystemClassLoader = useSystemClassLoader;
}
/**
* Should be called <b>right before</b> any spring context refresh This forces all calls to
* getService to wait until <code>doneRefreshingContext</code> is called
*/
public void startRefreshingContext() {
synchronized (refreshingContext) {
refreshingContext = true;
}
}
/**
* Should be called <b>right after</b> any spring context refresh This wakes up all calls to
* getService that were waiting because <code>startRefreshingContext</code> was called
*/
public void doneRefreshingContext() {
synchronized (refreshingContext) {
refreshingContext.notifyAll();
refreshingContext = false;
}
}
/**
* Returns true/false whether startRefreshingContext() has been called without a subsequent call
* to doneRefreshingContext() yet. All methods involved in starting/stopping a module should
* call this if a service method is needed -- otherwise a deadlock will occur.
*
* @return true/false whether the services are currently blocking waiting for a call to
* doneRefreshingContext()
*/
public boolean isRefreshingContext() {
return refreshingContext.booleanValue();
}
/**
* Retrieves all Beans which have been registered in the Spring {@link ApplicationContext} that
* match the given object type (including subclasses).
* <p>
* <b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i> check nested
* beans which might match the specified type as well.
*
* @see ApplicationContext#getBeansOfType(Class)
* @param type the type of Bean to retrieve from the Spring {@link ApplicationContext}
* @return a List of all registered Beans that are valid instances of the passed type
* @since 1.5
* @should return a list of all registered beans of the passed type
* @should return beans registered in a module
* @should return an empty list if no beans have been registered of the passed type
*/
public <T> List<T> getRegisteredComponents(Class<T> type) {
Map<String, T> m = getRegisteredComponents(applicationContext, type);
log.debug("getRegisteredComponents(" + type + ") = " + m);
return new ArrayList<T>(m.values());
}
/**
* Private method which returns all components registered in a Spring applicationContext of a given type
* This method recurses through each parent ApplicationContext
* @param context - The applicationContext to check
* @param type - The type of component to retrieve
* @return all components registered in a Spring applicationContext of a given type
*/
@SuppressWarnings("unchecked")
private <T> Map<String, T> getRegisteredComponents(ApplicationContext context, Class<T> type) {
Map<String, T> components = new HashMap<String, T>();
Map registeredComponents = context.getBeansOfType(type);
log.debug("getRegisteredComponents(" + context + ", " + type + ") = " + registeredComponents);
if (registeredComponents != null) {
components.putAll(registeredComponents);
}
if (context.getParent() != null) {
components.putAll(getRegisteredComponents(context.getParent(), type));
}
return components;
}
/**
* @param applicationContext the applicationContext to set
*/
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
| src/api/org/openmrs/api/context/ServiceContext.java | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.api.context;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aopalliance.aop.Advice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.api.APIException;
import org.openmrs.api.ActiveListService;
import org.openmrs.api.AdministrationService;
import org.openmrs.api.CohortService;
import org.openmrs.api.ConceptService;
import org.openmrs.api.DataSetService;
import org.openmrs.api.EncounterService;
import org.openmrs.api.FormService;
import org.openmrs.api.LocationService;
import org.openmrs.api.ObsService;
import org.openmrs.api.OrderService;
import org.openmrs.api.PatientService;
import org.openmrs.api.PatientSetService;
import org.openmrs.api.PersonService;
import org.openmrs.api.ProgramWorkflowService;
import org.openmrs.api.ReportService;
import org.openmrs.api.SerializationService;
import org.openmrs.api.UserService;
import org.openmrs.arden.ArdenService;
import org.openmrs.hl7.HL7Service;
import org.openmrs.logic.LogicService;
import org.openmrs.messagesource.MessageSourceService;
import org.openmrs.notification.AlertService;
import org.openmrs.notification.MessageService;
import org.openmrs.reporting.ReportObjectService;
import org.openmrs.scheduler.SchedulerService;
import org.openmrs.util.OpenmrsClassLoader;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Represents an OpenMRS <code>Service Context</code>, which returns the services represented
* throughout the system. <br/>
* <br/>
* This class should not be access directly, but rather used through the <code>Context</code> class. <br/>
* <br/>
* This class is essentially static and only one instance is kept because this is fairly
* heavy-weight. Spring takes care of filling in the actual service implementations via dependency
* injection. See the /metadata/api/spring/applicationContext-service.xml file. <br/>
* <br/>
* Module services are also accessed through this class. See {@link #getService(Class)}
*
* @see org.openmrs.api.context.Context
*/
public class ServiceContext implements ApplicationContextAware {
private static final Log log = LogFactory.getLog(ServiceContext.class);
private static ServiceContext instance;
private ApplicationContext applicationContext;
private Boolean refreshingContext = new Boolean(false);
/**
* Static variable holding whether or not to use the system classloader. By default this is
* false so the openmrs classloader is used instead
*/
private boolean useSystemClassLoader = false;
// Cached service objects
@SuppressWarnings("unchecked")
Map<Class, Object> services = new HashMap<Class, Object>();
// Advisors added to services by this service
@SuppressWarnings("unchecked")
Map<Class, Set<Advisor>> addedAdvisors = new HashMap<Class, Set<Advisor>>();
// Advice added to services by this service
@SuppressWarnings("unchecked")
Map<Class, Set<Advice>> addedAdvice = new HashMap<Class, Set<Advice>>();
/**
* The default constructor is private so as to keep only one instance per java vm.
*
* @see ServiceContext#getInstance()
*/
private ServiceContext() {
log.debug("Instantiating service context");
}
/**
* There should only be one ServiceContext per openmrs (java virtual machine). This method
* should be used when wanting to fetch the service context Note: The ServiceContext shouldn't
* be used independently. All calls should go through the Context
*
* @return This VM's current ServiceContext.
* @see org.openmrs.api.context.Context
*/
public static ServiceContext getInstance() {
if (instance == null)
instance = new ServiceContext();
return instance;
}
/**
* Null out the current instance of the ServiceContext. This should be used when modules are
* refreshing (being added/removed) and/or openmrs is shutting down
*/
@SuppressWarnings("unchecked")
public static void destroyInstance() {
if (instance != null && instance.services != null) {
if (log.isDebugEnabled()) {
for (Map.Entry<Class, Object> entry : instance.services.entrySet()) {
log.debug("Service - " + entry.getKey().getName() + ":" + entry.getValue());
}
}
// Remove advice and advisors that this service added
for (Class serviceClass : instance.services.keySet()) {
instance.removeAddedAOP(serviceClass);
}
if (instance.services != null) {
instance.services.clear();
instance.services = null;
}
if (instance.addedAdvisors != null) {
instance.addedAdvisors.clear();
instance.addedAdvisors = null;
}
if (instance.addedAdvice != null) {
instance.addedAdvice.clear();
instance.addedAdvice = null;
}
}
if (log.isDebugEnabled())
log.debug("Destroying ServiceContext instance: " + instance);
instance = null;
}
/**
* @return encounter-related services
*/
public EncounterService getEncounterService() {
return getService(EncounterService.class);
}
/**
* @return location services
*/
public LocationService getLocationService() {
return getService(LocationService.class);
}
/**
* @return observation services
*/
public ObsService getObsService() {
return getService(ObsService.class);
}
/**
* @return patientset-related services
*/
public PatientSetService getPatientSetService() {
return getService(PatientSetService.class);
}
/**
* @return cohort related service
*/
public CohortService getCohortService() {
return getService(CohortService.class);
}
/**
* @param cs cohort related service
*/
public void setCohortService(CohortService cs) {
setService(CohortService.class, cs);
}
/**
* @return order service
*/
public OrderService getOrderService() {
return getService(OrderService.class);
}
/**
* @return form service
*/
public FormService getFormService() {
return getService(FormService.class);
}
/**
* @return report object service
* @deprecated see reportingcompatibility module
*/
@Deprecated
public ReportObjectService getReportObjectService() {
return getService(ReportObjectService.class);
}
/**
* @return serialization service
*/
public SerializationService getSerializationService() {
return getService(SerializationService.class);
}
/**
* @return report service
* @deprecated see reportingcompatibility module
*/
@Deprecated
public ReportService getReportService() {
return getService(ReportService.class);
}
/**
* @return admin-related services
*/
public AdministrationService getAdministrationService() {
return getService(AdministrationService.class);
}
/**
* @return programWorkflowService
*/
public ProgramWorkflowService getProgramWorkflowService() {
return getService(ProgramWorkflowService.class);
}
/**
* @return ardenService
*/
public ArdenService getArdenService() {
return getService(ArdenService.class);
}
/**
* @return logicService
*/
public LogicService getLogicService() {
return getService(LogicService.class);
}
/**
* @return scheduler service
*/
public SchedulerService getSchedulerService() {
return getService(SchedulerService.class);
}
/**
* Set the scheduler service.
*
* @param schedulerService
*/
public void setSchedulerService(SchedulerService schedulerService) {
setService(SchedulerService.class, schedulerService);
}
/**
* @return alert service
*/
public AlertService getAlertService() {
return getService(AlertService.class);
}
/**
* @param alertService
*/
public void setAlertService(AlertService alertService) {
setService(AlertService.class, alertService);
}
/**
* @param programWorkflowService
*/
public void setProgramWorkflowService(ProgramWorkflowService programWorkflowService) {
setService(ProgramWorkflowService.class, programWorkflowService);
}
/**
* @param ardenService
*/
public void setArdenService(ArdenService ardenService) {
setService(ArdenService.class, ardenService);
}
/**
* @param logicService
*/
public void setLogicService(LogicService logicService) {
setService(LogicService.class, logicService);
}
/**
* @return message service
*/
public MessageService getMessageService() {
return getService(MessageService.class);
}
/**
* Sets the message service.
*
* @param messageService
*/
public void setMessageService(MessageService messageService) {
setService(MessageService.class, messageService);
}
/**
* @return the hl7Service
*/
public HL7Service getHL7Service() {
return getService(HL7Service.class);
}
/**
* @param hl7Service the hl7Service to set
*/
// TODO spring is demanding that this be hl7Service:setHl7Service and not hL7Service:setHL7Service. why?
public void setHl7Service(HL7Service hl7Service) {
setService(HL7Service.class, hl7Service);
}
/**
* @param administrationService the administrationService to set
*/
public void setAdministrationService(AdministrationService administrationService) {
setService(AdministrationService.class, administrationService);
}
/**
* @param encounterService the encounterService to set
*/
public void setEncounterService(EncounterService encounterService) {
setService(EncounterService.class, encounterService);
}
/**
* @param locationService the LocationService to set
*/
public void setLocationService(LocationService locationService) {
setService(LocationService.class, locationService);
}
/**
* @param formService the formService to set
*/
public void setFormService(FormService formService) {
setService(FormService.class, formService);
}
/**
* @param obsService the obsService to set
*/
public void setObsService(ObsService obsService) {
setService(ObsService.class, obsService);
}
/**
* @param orderService the orderService to set
*/
public void setOrderService(OrderService orderService) {
setService(OrderService.class, orderService);
}
/**
* @param patientSetService the patientSetService to set
*/
public void setPatientSetService(PatientSetService patientSetService) {
setService(PatientSetService.class, patientSetService);
}
/**
* @param reportObjectService the reportObjectService to set
* @deprecated see reportingcompatibility module
*/
@Deprecated
public void setReportObjectService(ReportObjectService reportObjectService) {
setService(ReportObjectService.class, reportObjectService);
}
/**
* @param reportService
* @deprecated see reportingcompatibility module
*/
@Deprecated
public void setReportService(ReportService reportService) {
setService(ReportService.class, reportService);
}
/**
* @param serializationService
*/
public void setSerializationService(SerializationService serializationService) {
setService(SerializationService.class, serializationService);
}
/**
* @param dataSetService
* @deprecated see reportingcompatibility module
*/
@Deprecated
public void setDataSetService(DataSetService dataSetService) {
setService(DataSetService.class, dataSetService);
}
/**
* @return the DataSetService
* @deprecated see reportingcompatibility module
*/
@Deprecated
public DataSetService getDataSetService() {
return getService(DataSetService.class);
}
/**
* @return patient related services
*/
public PatientService getPatientService() {
return getService(PatientService.class);
}
/**
* @param patientService the patientService to set
*/
public void setPatientService(PatientService patientService) {
setService(PatientService.class, patientService);
}
/**
* @return person related services
*/
public PersonService getPersonService() {
return getService(PersonService.class);
}
/**
* @param personService the personService to set
*/
public void setPersonService(PersonService personService) {
setService(PersonService.class, personService);
}
/**
* @return concept related services
*/
public ConceptService getConceptService() {
return getService(ConceptService.class);
}
/**
* @param conceptService the conceptService to set
*/
public void setConceptService(ConceptService conceptService) {
setService(ConceptService.class, conceptService);
}
/**
* @return user-related services
*/
public UserService getUserService() {
return getService(UserService.class);
}
/**
* @param userService the userService to set
*/
public void setUserService(UserService userService) {
setService(UserService.class, userService);
}
/**
* Gets the MessageSourceService used in the context.
*
* @return MessageSourceService
*/
public MessageSourceService getMessageSourceService() {
return getService(MessageSourceService.class);
}
/**
* Sets the MessageSourceService used in the context.
*
* @param messageSourceService the MessageSourceService to use
*/
public void setMessageSourceService(MessageSourceService messageSourceService) {
setService(MessageSourceService.class, messageSourceService);
}
/**
* Gets the ActiveListService used in the context.
*
* @return ActiveListService
*/
public ActiveListService getActiveListService() {
return getService(ActiveListService.class);
}
/**
* Sets the ActiveListService used in the context
*/
public void setActiveListService(ActiveListService activeListService) {
setService(ActiveListService.class, activeListService);
}
/**
* @param cls
* @param advisor
*/
@SuppressWarnings("unchecked")
public void addAdvisor(Class cls, Advisor advisor) {
Advised advisedService = (Advised) services.get(cls);
advisedService.addAdvisor(advisor);
if (addedAdvice.get(cls) == null)
addedAdvisors.put(cls, new HashSet<Advisor>());
getAddedAdvisors(cls).add(advisor);
}
/**
* @param cls
* @param advice
*/
@SuppressWarnings("unchecked")
public void addAdvice(Class cls, Advice advice) {
Advised advisedService = (Advised) services.get(cls);
advisedService.addAdvice(advice);
if (addedAdvice.get(cls) == null)
addedAdvice.put(cls, new HashSet<Advice>());
getAddedAdvice(cls).add(advice);
}
/**
* @param cls
* @param advisor
*/
@SuppressWarnings("unchecked")
public void removeAdvisor(Class cls, Advisor advisor) {
Advised advisedService = (Advised) services.get(cls);
advisedService.removeAdvisor(advisor);
getAddedAdvisors(cls).remove(advisor);
}
/**
* @param cls
* @param advice
*/
@SuppressWarnings("unchecked")
public void removeAdvice(Class cls, Advice advice) {
Advised advisedService = (Advised) services.get(cls);
advisedService.removeAdvice(advice);
getAddedAdvice(cls).remove(advice);
}
/**
* Moves advisors and advice added by ServiceContext from the source service to the target one.
*
* @param source the existing service
* @param target the new service
*/
@SuppressWarnings("unchecked")
private void moveAddedAOP(Advised source, Advised target) {
Class serviceClass = source.getClass();
Set<Advisor> existingAdvisors = getAddedAdvisors(serviceClass);
for (Advisor advisor : existingAdvisors) {
target.addAdvisor(advisor);
source.removeAdvisor(advisor);
}
Set<Advice> existingAdvice = getAddedAdvice(serviceClass);
for (Advice advice : existingAdvice) {
target.addAdvice(advice);
source.removeAdvice(advice);
}
}
/**
* Removes all advice and advisors added by ServiceContext.
*
* @param cls the class of the cached service to cleanup
*/
@SuppressWarnings("unchecked")
private void removeAddedAOP(Class cls) {
removeAddedAdvisors(cls);
removeAddedAdvice(cls);
}
/**
* Removes all the advisors added by ServiceContext.
*
* @param cls the class of the cached service to cleanup
*/
@SuppressWarnings("unchecked")
private void removeAddedAdvisors(Class cls) {
Advised advisedService = (Advised) services.get(cls);
Set<Advisor> advisorsToRemove = addedAdvisors.get(cls);
if (advisedService != null && advisorsToRemove != null) {
for (Advisor advisor : advisorsToRemove.toArray(new Advisor[] {}))
removeAdvisor(cls, advisor);
}
}
/**
* Returns the set of advisors added by ServiceContext.
*
* @param cls the class of the cached service
* @return the set of advisors or an empty set
*/
@SuppressWarnings("unchecked")
private Set<Advisor> getAddedAdvisors(Class cls) {
Set<Advisor> result = addedAdvisors.get(cls);
return result == null ? Collections.EMPTY_SET : result;
}
/**
* Removes all the advice added by the ServiceContext.
*
* @param cls the class of the caches service to cleanup
*/
@SuppressWarnings("unchecked")
private void removeAddedAdvice(Class cls) {
Advised advisedService = (Advised) services.get(cls);
Set<Advice> adviceToRemove = addedAdvice.get(cls);
if (advisedService != null && adviceToRemove != null) {
for (Advice advice : adviceToRemove.toArray(new Advice[] {}))
removeAdvice(cls, advice);
}
}
/**
* Returns the set of advice added by ServiceContext.
*
* @param cls the class of the cached service
* @return the set of advice or an empty set
*/
@SuppressWarnings("unchecked")
private Set<Advice> getAddedAdvice(Class cls) {
Set<Advice> result = addedAdvice.get(cls);
return result == null ? Collections.EMPTY_SET : result;
}
/**
* Returns the current proxy that is stored for the Class <code>cls</code>
*
* @param cls
* @return Object that is a proxy for the <code>cls</code> class
*/
@SuppressWarnings("unchecked")
public <T extends Object> T getService(Class<? extends T> cls) {
if (log.isTraceEnabled())
log.trace("Getting service: " + cls);
// if the context is refreshing, wait until it is
// done -- otherwise a null service might be returned
synchronized (refreshingContext) {
if (refreshingContext.booleanValue())
try {
log.warn("Waiting to get service: " + cls + " while the context is being refreshed");
refreshingContext.wait();
log.warn("Finished waiting to get service " + cls + " while the context was being refreshed");
}
catch (InterruptedException e) {
log.warn("Refresh lock was interrupted", e);
}
}
Object service = services.get(cls);
if (service == null)
throw new APIException("Service not found: " + cls);
return (T) service;
}
/**
* Allow other services to be added to our service layer
*
* @param cls Interface to proxy
* @param classInstance the actual instance of the <code>cls</code> interface
*/
@SuppressWarnings("unchecked")
public void setService(Class cls, Object classInstance) {
log.debug("Setting service: " + cls);
if (cls != null && classInstance != null) {
try {
Advised cachedService = (Advised) services.get(cls);
boolean noExistingService = cachedService == null;
boolean replacingService = cachedService != null && cachedService != classInstance;
boolean serviceAdvised = classInstance instanceof Advised;
if (noExistingService || replacingService) {
Advised advisedService;
if (!serviceAdvised) {
// Adding a bare service, wrap with AOP proxy
Class[] interfaces = { cls };
ProxyFactory factory = new ProxyFactory(interfaces);
factory.setTarget(classInstance);
advisedService = (Advised) factory.getProxy(OpenmrsClassLoader.getInstance());
} else
advisedService = (Advised) classInstance;
if (replacingService)
moveAddedAOP(cachedService, advisedService);
services.put(cls, advisedService);
}
log.debug("Service: " + cls + " set successfully");
}
catch (Exception e) {
throw new APIException("Unable to create proxy factory for: " + classInstance.getClass().getName(), e);
}
}
}
/**
* Allow other services to be added to our service layer <br/>
* <br/>
* Classes will be found/loaded with the ModuleClassLoader <br/>
* <br/>
* <code>params</code>[0] = string representing the service interface<br/>
* <code>params</code>[1] = service instance
*
* @param params list of parameters
*/
@SuppressWarnings("unchecked")
public void setModuleService(List<Object> params) {
String classString = (String) params.get(0);
Object classInstance = params.get(1);
if (classString == null || classInstance == null) {
throw new APIException("Unable to find classString or classInstance in params");
}
Class cls = null;
// load the given 'classString' class from either the openmrs class
// loader or the system class loader depending on if we're in a testing
// environment or not (system == testing, openmrs == normal)
try {
if (useSystemClassLoader == false) {
cls = OpenmrsClassLoader.getInstance().loadClass(classString);
if (cls != null && log.isDebugEnabled()) {
try {
log.debug("cls classloader: " + cls.getClass().getClassLoader() + " uid: "
+ cls.getClass().getClassLoader().hashCode());
}
catch (Exception e) { /*pass*/}
}
} else if (useSystemClassLoader == true) {
try {
cls = Class.forName(classString);
if (log.isDebugEnabled()) {
log.debug("cls2 classloader: " + cls.getClass().getClassLoader() + " uid: "
+ cls.getClass().getClassLoader().hashCode());
log.debug("cls==cls2: " + String.valueOf(cls == cls));
}
}
catch (Exception e) { /*pass*/}
}
}
catch (ClassNotFoundException e) {
throw new APIException("Unable to set module service: " + classString, e);
}
// add this module service to the normal list of services
setService(cls, classInstance);
}
/**
* Set this service context to use the system class loader if the
* <code>useSystemClassLoader</code> is set to true. If false, the openmrs class loader is used
* to load module services
*
* @param useSystemClassLoader true/false whether to use the system class loader
*/
public void setUseSystemClassLoader(boolean useSystemClassLoader) {
this.useSystemClassLoader = useSystemClassLoader;
}
/**
* Should be called <b>right before</b> any spring context refresh This forces all calls to
* getService to wait until <code>doneRefreshingContext</code> is called
*/
public void startRefreshingContext() {
synchronized (refreshingContext) {
refreshingContext = true;
}
}
/**
* Should be called <b>right after</b> any spring context refresh This wakes up all calls to
* getService that were waiting because <code>startRefreshingContext</code> was called
*/
public void doneRefreshingContext() {
synchronized (refreshingContext) {
refreshingContext.notifyAll();
refreshingContext = false;
}
}
/**
* Returns true/false whether startRefreshingContext() has been called without a subsequent call
* to doneRefreshingContext() yet. All methods involved in starting/stopping a module should
* call this if a service method is needed -- otherwise a deadlock will occur.
*
* @return true/false whether the services are currently blocking waiting for a call to
* doneRefreshingContext()
*/
public boolean isRefreshingContext() {
return refreshingContext.booleanValue();
}
/**
* Retrieves all Beans which have been registered in the Spring {@link ApplicationContext} that
* match the given object type (including subclasses).
* <p>
* <b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i> check nested
* beans which might match the specified type as well.
*
* @see ApplicationContext#getBeansOfType(Class)
* @param type the type of Bean to retrieve from the Spring {@link ApplicationContext}
* @return a List of all registered Beans that are valid instances of the passed type
* @since 1.5
* @should return a list of all registered beans of the passed type
* @should return beans registered in a module
* @should return an empty list if no beans have been registered of the passed type
*/
public <T> List<T> getRegisteredComponents(Class<T> type) {
Map<String, T> m = getRegisteredComponents(applicationContext, type);
log.debug("getRegisteredComponents(" + type + ") = " + m);
return new ArrayList<T>(m.values());
}
/**
* Private method which returns all components registered in a Spring applicationContext of a given type
* This method recurses through each parent ApplicationContext
* @param context - The applicationContext to check
* @param type - The type of component to retrieve
* @return all components registered in a Spring applicationContext of a given type
*/
@SuppressWarnings("unchecked")
private <T> Map<String, T> getRegisteredComponents(ApplicationContext context, Class<T> type) {
Map<String, T> components = new HashMap<String, T>();
Map registeredComponents = context.getBeansOfType(type);
log.debug("getRegisteredComponents(" + context + ", " + type + ") = " + registeredComponents);
if (registeredComponents != null) {
components.putAll(registeredComponents);
}
if (context.getParent() != null) {
components.putAll(getRegisteredComponents(context.getParent(), type));
}
return components;
}
/**
* @param applicationContext the applicationContext to set
*/
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
| for TRUNK-1604 fixing ServiceContext to not load advice or advisors twice
git-svn-id: ce3478dfdc990238714fcdf4fc6855b7489218cf@14331 5bac5841-c719-aa4e-b3fe-cce5062f897a
| src/api/org/openmrs/api/context/ServiceContext.java | for TRUNK-1604 fixing ServiceContext to not load advice or advisors twice |
|
Java | lgpl-2.1 | 9a11f2d8e6ec262df2ff2d1ad5c139c40636bf24 | 0 | svn2github/beast-mcmc,svn2github/beast-mcmc,armanbilge/BEAST_sandbox,armanbilge/BEAST_sandbox,svn2github/beast-mcmc,armanbilge/BEAST_sandbox,svn2github/beast-mcmc,svn2github/beast-mcmc,armanbilge/BEAST_sandbox,armanbilge/BEAST_sandbox | /*
* PartitionModelPanel.java
*
* Copyright (c) 2002-2011 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.app.beauti.ancestralStatesPanel;
import dr.app.beauti.components.ancestralstates.AncestralStatesComponentOptions;
import dr.app.beauti.components.sequenceerror.SequenceErrorModelComponentOptions;
import dr.app.beauti.options.AbstractPartitionData;
import dr.app.beauti.options.BeautiOptions;
import dr.app.beauti.types.SequenceErrorType;
import dr.app.beauti.util.PanelUtils;
import dr.app.util.OSType;
import dr.evolution.datatype.DataType;
import dr.evolution.util.Taxa;
import jam.panels.OptionsPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Walter Xie
*/
public class AncestralStatesOptionsPanel extends OptionsPanel {
private static final String ROBUST_COUNTING_TOOL_TIP = "<html>"
+ "Enable counting of reconstructed number of substitutions as described in<br>"
+ "Minin & Suchard (2008). These will be annotated directly in the<br>"
+ "logged trees.</html>";
private static final String DNDS_ROBUST_COUNTING_TOOL_TIP = "<html>"
+ "Enable counting of synonymous and non-synonymous substitution as described in<br>"
+ "O'Brien, Minin & Suchard (2009) and Lemey, Minin, Bielejec, Kosakovsky-Pond &<br>"
+ "Suchard (2012). This model requires a 3-partition codon model to be<br>"
+ "selected in the Site model for this partition and NO Site Heterogeneity Model.</html>";
// Components
private static final long serialVersionUID = -1645661616353099424L;
private final AbstractPartitionData partition;
private JCheckBox ancestralReconstructionCheck = new JCheckBox(
"Reconstruct states at all ancestors");
private JCheckBox mrcaReconstructionCheck = new JCheckBox(
"Reconstruct states at ancestor:");
private JComboBox mrcaReconstructionCombo = new JComboBox();
private JCheckBox countingCheck = new JCheckBox(
"Reconstruct state change counts");
private JCheckBox dNdSRobustCountingCheck = new JCheckBox(
"Reconstruct synonymous/non-synonymous change counts");
private JTextArea dNnSText = new JTextArea(
"This model requires a 3-partition codon model to be selected in the Site model " +
"for this partition and NO Site Heterogeneity Model before it can be selected.");
// dNdS robust counting is automatic if RC is turned on for a codon
// partitioned data set.
// private JCheckBox dNdSCountingCheck = new JCheckBox(
// "Reconstruct synonymous/non-synonymous counts");
final BeautiOptions options;
// JComboBox errorModelCombo = new JComboBox(EnumSet.range(SequenceErrorType.NO_ERROR, SequenceErrorType.BASE_ALL).toArray());
JComboBox errorModelCombo = new JComboBox(SequenceErrorType.values());
AncestralStatesComponentOptions ancestralStatesComponent;
SequenceErrorModelComponentOptions sequenceErrorComponent;
public AncestralStatesOptionsPanel(final AncestralStatesPanel ancestralStatesPanel, final BeautiOptions options, final AbstractPartitionData partition) {
super(12, (OSType.isMac() ? 6 : 24));
setOpaque(false);
this.partition = partition;
this.options = options;
PanelUtils.setupComponent(ancestralReconstructionCheck);
ancestralReconstructionCheck
.setToolTipText("<html>"
+ "Reconstruct posterior realizations of the states at ancestral nodes.<br>" +
"These will be annotated directly in the logged trees.</html>");
PanelUtils.setupComponent(mrcaReconstructionCheck);
mrcaReconstructionCheck
.setToolTipText("<html>"
+ "Reconstruct posterior realizations of the states at a specific common<br>" +
"ancestor defined by a taxon set. This will be recorded in the log file.</html>");
PanelUtils.setupComponent(mrcaReconstructionCombo);
mrcaReconstructionCombo
.setToolTipText("<html>"
+ "Reconstruct posterior realizations of the states at a specific common.<br>" +
"ancestor defined by a taxon set. This will be recorded in the log file.</html>");
PanelUtils.setupComponent(countingCheck);
countingCheck.setToolTipText(ROBUST_COUNTING_TOOL_TIP);
PanelUtils.setupComponent(dNdSRobustCountingCheck);
dNdSRobustCountingCheck.setToolTipText(DNDS_ROBUST_COUNTING_TOOL_TIP);
// ////////////////////////
PanelUtils.setupComponent(errorModelCombo);
errorModelCombo.setToolTipText("<html>Select how to model sequence error or<br>"
+ "post-mortem DNA damage.</html>");
// Set the initial options
ancestralStatesComponent = (AncestralStatesComponentOptions)options.getComponentOptions(AncestralStatesComponentOptions.class);
// ancestralStatesComponent.createParameters(options);
ancestralReconstructionCheck.setSelected(ancestralStatesComponent.reconstructAtNodes(partition));
mrcaReconstructionCheck.setSelected(ancestralStatesComponent.reconstructAtMRCA(partition));
mrcaReconstructionCombo.setSelectedItem(ancestralStatesComponent.getMRCATaxonSet(partition));
countingCheck.setSelected(ancestralStatesComponent.isCountingStates(partition));
dNdSRobustCountingCheck.setSelected(ancestralStatesComponent.dNdSRobustCounting(partition));
sequenceErrorComponent = (SequenceErrorModelComponentOptions)options.getComponentOptions(SequenceErrorModelComponentOptions.class);
// sequenceErrorComponent.createParameters(options); // this cannot create correct param here, because of improper design
errorModelCombo.setSelectedItem(sequenceErrorComponent.getSequenceErrorType(partition));
setupPanel();
ItemListener listener = new ItemListener() {
public void itemStateChanged(final ItemEvent itemEvent) {
optionsChanged();
ancestralStatesPanel.fireModelChanged();
// The following is only necessary is simpleCounting XOR robustCounting
// if (itemEvent.getItem() == countingCheck) {
// boolean enableRC = !countingCheck.isSelected() && ancestralStatesComponent.dNdSRobustCountingAvailable(partition);
// dNdSRobustCountingCheck.setEnabled(enableRC);
// dNnSText.setEnabled(enableRC);
// }
//
// if (itemEvent.getItem() == dNdSRobustCountingCheck) {
// boolean enableSimpleCounting = !dNdSRobustCountingCheck.isSelected();
// countingCheck.setEnabled(enableSimpleCounting);
// }
}
};
ancestralReconstructionCheck.addItemListener(listener);
mrcaReconstructionCheck.addItemListener(listener);
mrcaReconstructionCombo.addItemListener(listener);
countingCheck.addItemListener(listener);
dNdSRobustCountingCheck.addItemListener(listener);
errorModelCombo.addItemListener(listener);
}
private void optionsChanged() {
if (isUpdating) return;
ancestralStatesComponent.setReconstructAtNodes(partition, ancestralReconstructionCheck.isSelected());
ancestralStatesComponent.setReconstructAtMRCA(partition, mrcaReconstructionCheck.isSelected());
mrcaReconstructionCombo.setEnabled(mrcaReconstructionCheck.isSelected());
if (mrcaReconstructionCombo.getSelectedIndex() == 0) {
// root node
ancestralStatesComponent.setMRCATaxonSet(partition, null);
} else {
String text = (String) mrcaReconstructionCombo.getSelectedItem();
String taxonSetId = text.substring(5,text.length() - 1);
ancestralStatesComponent.setMRCATaxonSet(partition, taxonSetId);
}
ancestralStatesComponent.setCountingStates(partition, countingCheck.isSelected());
// ancestralStatesComponent.setDNdSRobustCounting(partition, robustCountingCheck.isSelected());
ancestralStatesComponent.setDNdSRobustCounting(partition, dNdSRobustCountingCheck.isSelected());
sequenceErrorComponent.setSequenceErrorType(partition, (SequenceErrorType)errorModelCombo.getSelectedItem());
sequenceErrorComponent.createParameters(options);
}
/**
* Lays out the appropriate components in the panel for this partition
* model.
*/
void setupPanel() {
isUpdating = true;
String selectedItem = (String)mrcaReconstructionCombo.getSelectedItem();
if (mrcaReconstructionCombo.getItemCount() > 0) {
mrcaReconstructionCombo.removeAllItems();
}
mrcaReconstructionCombo.addItem("Tree Root");
if (options.taxonSets.size() > 0) {
for (Taxa taxonSet : options.taxonSets) {
mrcaReconstructionCombo.addItem("MRCA("+ taxonSet.getId() + ")");
}
if (selectedItem != null) {
mrcaReconstructionCombo.setSelectedItem(selectedItem);
}
}
mrcaReconstructionCombo.setEnabled(mrcaReconstructionCheck.isSelected());
boolean ancestralReconstructionAvailable = true;
boolean countingAvailable = true;
boolean dNdSRobustCountingAvailable = false;
boolean errorModelAvailable = false;
switch (partition.getDataType().getType()) {
case DataType.NUCLEOTIDES:
errorModelAvailable = true;
dNdSRobustCountingAvailable = true; // but will be disabled if not codon partitioned
break;
case DataType.AMINO_ACIDS:
case DataType.GENERAL:
case DataType.TWO_STATES:
break;
case DataType.CONTINUOUS:
countingAvailable = false;
break;
case DataType.MICRO_SAT:
ancestralReconstructionAvailable = false;
countingAvailable = false;
break;
default:
throw new IllegalArgumentException("Unsupported data type");
}
removeAll();
if (ancestralReconstructionAvailable) {
addSpanningComponent(new JLabel("Ancestral State Reconstruction:"));
addComponent(ancestralReconstructionCheck);
FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
layout.setHgap(0);
JPanel panel = new JPanel(layout);
panel.setOpaque(false);
panel.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
panel.add(mrcaReconstructionCheck);
panel.add(mrcaReconstructionCombo);
addComponent(panel);
}
if (countingAvailable) {
if (ancestralReconstructionAvailable) {
addSeparator();
}
addSpanningComponent(new JLabel("State Change Count Reconstruction:"));
JTextArea text = new JTextArea(
"Select this option to reconstruct counts of state changes using " +
"Markov Jumps. This approach is described in Minin & Suchard (2008).");
text.setColumns(40);
PanelUtils.setupComponent(text);
addComponent(text);
addComponent(countingCheck);
boolean enableSimpleCounting = true;
// TODO Simple counting is currently not available for codon partitioned models due to BEAUti limitation
if (ancestralStatesComponent.dNdSRobustCountingAvailable(partition)) {
enableSimpleCounting = false;
countingCheck.setSelected(false);
}
countingCheck.setEnabled(enableSimpleCounting);
if (dNdSRobustCountingAvailable) {
addSeparator();
text = new JTextArea(
"Renaissance counting: select this option to reconstruct counts of synonymous and nonsynonymous " +
"changes using Robust Counting. This approach is described in O'Brien, Minin " +
"& Suchard (2009) and Lemey, Minin, Bielejec, Kosakovsky-Pond & Suchard " +
"(2012):");
text.setColumns(40);
PanelUtils.setupComponent(text);
addComponent(text);
addComponent(dNdSRobustCountingCheck);
dNnSText.setColumns(40);
dNnSText.setBorder(BorderFactory.createEmptyBorder(0, 32, 0, 0));
PanelUtils.setupComponent(dNnSText);
addComponent(dNnSText);
boolean enableRC = ancestralStatesComponent.dNdSRobustCountingAvailable(partition);
// && !ancestralStatesComponent.isCountingStates(partition);
dNdSRobustCountingCheck.setEnabled(enableRC);
dNnSText.setEnabled(enableRC);
if (!enableRC) {
dNdSRobustCountingCheck.setSelected(false);
}
}
}
if (errorModelAvailable) {
if (ancestralReconstructionAvailable || countingAvailable) {
addSeparator();
}
addSpanningComponent(new JLabel("Sequence error model:"));
addComponentWithLabel("Error Model:", errorModelCombo);
}
isUpdating = false;
}
private boolean isUpdating = false;
}
| src/dr/app/beauti/ancestralStatesPanel/AncestralStatesOptionsPanel.java | /*
* PartitionModelPanel.java
*
* Copyright (c) 2002-2011 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.app.beauti.ancestralStatesPanel;
import dr.app.beauti.components.ancestralstates.AncestralStatesComponentOptions;
import dr.app.beauti.components.sequenceerror.SequenceErrorModelComponentOptions;
import dr.app.beauti.options.AbstractPartitionData;
import dr.app.beauti.options.BeautiOptions;
import dr.app.beauti.types.SequenceErrorType;
import dr.app.beauti.util.PanelUtils;
import dr.app.util.OSType;
import dr.evolution.datatype.DataType;
import dr.evolution.util.Taxa;
import jam.panels.OptionsPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Walter Xie
*/
public class AncestralStatesOptionsPanel extends OptionsPanel {
private static final String ROBUST_COUNTING_TOOL_TIP = "<html>"
+ "Enable counting of reconstructed number of substitutions as described in<br>"
+ "Minin & Suchard (2008). These will be annotated directly in the<br>"
+ "logged trees.</html>";
private static final String DNDS_ROBUST_COUNTING_TOOL_TIP = "<html>"
+ "Enable counting of synonymous and non-synonymous substitution as described in<br>"
+ "O'Brien, Minin & Suchard (2009) and Lemey, Minin, Bielejec, Kosakovsky-Pond &<br>"
+ "Suchard (in preparation). This model requires a 3-partition codon model to be<br>"
+ "selected in the Site model for this partition.</html>";
// Components
private static final long serialVersionUID = -1645661616353099424L;
private final AbstractPartitionData partition;
private JCheckBox ancestralReconstructionCheck = new JCheckBox(
"Reconstruct states at all ancestors");
private JCheckBox mrcaReconstructionCheck = new JCheckBox(
"Reconstruct states at ancestor:");
private JComboBox mrcaReconstructionCombo = new JComboBox();
private JCheckBox countingCheck = new JCheckBox(
"Reconstruct state change counts");
private JCheckBox dNdSRobustCountingCheck = new JCheckBox(
"Reconstruct synonymous/non-synonymous change counts");
private JTextArea dNnSText = new JTextArea(
"This model requires a 3-partition codon model to be selected in " +
"the Site model for this partition before it can be selected.");
// dNdS robust counting is automatic if RC is turned on for a codon
// partitioned data set.
// private JCheckBox dNdSCountingCheck = new JCheckBox(
// "Reconstruct synonymous/non-synonymous counts");
final BeautiOptions options;
// JComboBox errorModelCombo = new JComboBox(EnumSet.range(SequenceErrorType.NO_ERROR, SequenceErrorType.BASE_ALL).toArray());
JComboBox errorModelCombo = new JComboBox(SequenceErrorType.values());
AncestralStatesComponentOptions ancestralStatesComponent;
SequenceErrorModelComponentOptions sequenceErrorComponent;
public AncestralStatesOptionsPanel(final AncestralStatesPanel ancestralStatesPanel, final BeautiOptions options, final AbstractPartitionData partition) {
super(12, (OSType.isMac() ? 6 : 24));
setOpaque(false);
this.partition = partition;
this.options = options;
PanelUtils.setupComponent(ancestralReconstructionCheck);
ancestralReconstructionCheck
.setToolTipText("<html>"
+ "Reconstruct posterior realizations of the states at ancestral nodes.<br>" +
"These will be annotated directly in the logged trees.</html>");
PanelUtils.setupComponent(mrcaReconstructionCheck);
mrcaReconstructionCheck
.setToolTipText("<html>"
+ "Reconstruct posterior realizations of the states at a specific common<br>" +
"ancestor defined by a taxon set. This will be recorded in the log file.</html>");
PanelUtils.setupComponent(mrcaReconstructionCombo);
mrcaReconstructionCombo
.setToolTipText("<html>"
+ "Reconstruct posterior realizations of the states at a specific common.<br>" +
"ancestor defined by a taxon set. This will be recorded in the log file.</html>");
PanelUtils.setupComponent(countingCheck);
countingCheck.setToolTipText(ROBUST_COUNTING_TOOL_TIP);
PanelUtils.setupComponent(dNdSRobustCountingCheck);
dNdSRobustCountingCheck.setToolTipText(DNDS_ROBUST_COUNTING_TOOL_TIP);
// ////////////////////////
PanelUtils.setupComponent(errorModelCombo);
errorModelCombo.setToolTipText("<html>Select how to model sequence error or<br>"
+ "post-mortem DNA damage.</html>");
// Set the initial options
ancestralStatesComponent = (AncestralStatesComponentOptions)options.getComponentOptions(AncestralStatesComponentOptions.class);
// ancestralStatesComponent.createParameters(options);
ancestralReconstructionCheck.setSelected(ancestralStatesComponent.reconstructAtNodes(partition));
mrcaReconstructionCheck.setSelected(ancestralStatesComponent.reconstructAtMRCA(partition));
mrcaReconstructionCombo.setSelectedItem(ancestralStatesComponent.getMRCATaxonSet(partition));
countingCheck.setSelected(ancestralStatesComponent.isCountingStates(partition));
dNdSRobustCountingCheck.setSelected(ancestralStatesComponent.dNdSRobustCounting(partition));
sequenceErrorComponent = (SequenceErrorModelComponentOptions)options.getComponentOptions(SequenceErrorModelComponentOptions.class);
// sequenceErrorComponent.createParameters(options); // this cannot create correct param here, because of improper design
errorModelCombo.setSelectedItem(sequenceErrorComponent.getSequenceErrorType(partition));
setupPanel();
ItemListener listener = new ItemListener() {
public void itemStateChanged(final ItemEvent itemEvent) {
optionsChanged();
ancestralStatesPanel.fireModelChanged();
// The following is only necessary is simpleCounting XOR robustCounting
// if (itemEvent.getItem() == countingCheck) {
// boolean enableRC = !countingCheck.isSelected() && ancestralStatesComponent.dNdSRobustCountingAvailable(partition);
// dNdSRobustCountingCheck.setEnabled(enableRC);
// dNnSText.setEnabled(enableRC);
// }
//
// if (itemEvent.getItem() == dNdSRobustCountingCheck) {
// boolean enableSimpleCounting = !dNdSRobustCountingCheck.isSelected();
// countingCheck.setEnabled(enableSimpleCounting);
// }
}
};
ancestralReconstructionCheck.addItemListener(listener);
mrcaReconstructionCheck.addItemListener(listener);
mrcaReconstructionCombo.addItemListener(listener);
countingCheck.addItemListener(listener);
dNdSRobustCountingCheck.addItemListener(listener);
errorModelCombo.addItemListener(listener);
}
private void optionsChanged() {
if (isUpdating) return;
ancestralStatesComponent.setReconstructAtNodes(partition, ancestralReconstructionCheck.isSelected());
ancestralStatesComponent.setReconstructAtMRCA(partition, mrcaReconstructionCheck.isSelected());
mrcaReconstructionCombo.setEnabled(mrcaReconstructionCheck.isSelected());
if (mrcaReconstructionCombo.getSelectedIndex() == 0) {
// root node
ancestralStatesComponent.setMRCATaxonSet(partition, null);
} else {
String text = (String) mrcaReconstructionCombo.getSelectedItem();
String taxonSetId = text.substring(5,text.length() - 1);
ancestralStatesComponent.setMRCATaxonSet(partition, taxonSetId);
}
ancestralStatesComponent.setCountingStates(partition, countingCheck.isSelected());
// ancestralStatesComponent.setDNdSRobustCounting(partition, robustCountingCheck.isSelected());
ancestralStatesComponent.setDNdSRobustCounting(partition, dNdSRobustCountingCheck.isSelected());
sequenceErrorComponent.setSequenceErrorType(partition, (SequenceErrorType)errorModelCombo.getSelectedItem());
sequenceErrorComponent.createParameters(options);
}
/**
* Lays out the appropriate components in the panel for this partition
* model.
*/
void setupPanel() {
isUpdating = true;
String selectedItem = (String)mrcaReconstructionCombo.getSelectedItem();
if (mrcaReconstructionCombo.getItemCount() > 0) {
mrcaReconstructionCombo.removeAllItems();
}
mrcaReconstructionCombo.addItem("Tree Root");
if (options.taxonSets.size() > 0) {
for (Taxa taxonSet : options.taxonSets) {
mrcaReconstructionCombo.addItem("MRCA("+ taxonSet.getId() + ")");
}
if (selectedItem != null) {
mrcaReconstructionCombo.setSelectedItem(selectedItem);
}
}
mrcaReconstructionCombo.setEnabled(mrcaReconstructionCheck.isSelected());
boolean ancestralReconstructionAvailable = true;
boolean countingAvailable = true;
boolean dNdSRobustCountingAvailable = false;
boolean errorModelAvailable = false;
switch (partition.getDataType().getType()) {
case DataType.NUCLEOTIDES:
errorModelAvailable = true;
dNdSRobustCountingAvailable = true; // but will be disabled if not codon partitioned
break;
case DataType.AMINO_ACIDS:
case DataType.GENERAL:
case DataType.TWO_STATES:
break;
case DataType.CONTINUOUS:
countingAvailable = false;
break;
case DataType.MICRO_SAT:
ancestralReconstructionAvailable = false;
countingAvailable = false;
break;
default:
throw new IllegalArgumentException("Unsupported data type");
}
removeAll();
if (ancestralReconstructionAvailable) {
addSpanningComponent(new JLabel("Ancestral State Reconstruction:"));
addComponent(ancestralReconstructionCheck);
FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
layout.setHgap(0);
JPanel panel = new JPanel(layout);
panel.setOpaque(false);
panel.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
panel.add(mrcaReconstructionCheck);
panel.add(mrcaReconstructionCombo);
addComponent(panel);
}
if (countingAvailable) {
if (ancestralReconstructionAvailable) {
addSeparator();
}
addSpanningComponent(new JLabel("State Change Count Reconstruction:"));
JTextArea text = new JTextArea(
"Select this option to reconstruct counts of state changes using " +
"Markov Jumps. This approached is described in Minin & Suchard (2008).");
text.setColumns(40);
PanelUtils.setupComponent(text);
addComponent(text);
addComponent(countingCheck);
boolean enableSimpleCounting = true;
// TODO Simple counting is currently not available for codon partitioned models due to BEAUti limitation
if (ancestralStatesComponent.dNdSRobustCountingAvailable(partition)) {
enableSimpleCounting = false;
countingCheck.setSelected(false);
}
countingCheck.setEnabled(enableSimpleCounting);
if (dNdSRobustCountingAvailable) {
addSeparator();
text = new JTextArea(
"Select this option to reconstruct counts of synonymous and nonsynonymous " +
"changes using Robust Counting. This approached is described in O'Brien, Minin " +
"& Suchard (2009) and Lemey, Minin, Bielejec, Kosakovsky-Pond & Suchard " +
"(in preparation):");
text.setColumns(40);
PanelUtils.setupComponent(text);
addComponent(text);
addComponent(dNdSRobustCountingCheck);
dNnSText.setColumns(40);
dNnSText.setBorder(BorderFactory.createEmptyBorder(0, 32, 0, 0));
PanelUtils.setupComponent(dNnSText);
addComponent(dNnSText);
boolean enableRC = ancestralStatesComponent.dNdSRobustCountingAvailable(partition);
// && !ancestralStatesComponent.isCountingStates(partition);
dNdSRobustCountingCheck.setEnabled(enableRC);
dNnSText.setEnabled(enableRC);
if (!enableRC) {
dNdSRobustCountingCheck.setSelected(false);
}
}
}
if (errorModelAvailable) {
if (ancestralReconstructionAvailable || countingAvailable) {
addSeparator();
}
addSpanningComponent(new JLabel("Sequence error model:"));
addComponentWithLabel("Error Model:", errorModelCombo);
}
isUpdating = false;
}
private boolean isUpdating = false;
}
| text message changes for the renaissance counting method in AncestralStatesOptionsPanel
git-svn-id: 67bc77c75b8364e4e9cdff0eb6560f5818674cd8@5395 ca793f91-a31e-0410-b540-2769d408b6a1
| src/dr/app/beauti/ancestralStatesPanel/AncestralStatesOptionsPanel.java | text message changes for the renaissance counting method in AncestralStatesOptionsPanel |
|
Java | lgpl-2.1 | 36e09d8b75692473583c952e082c5c6d0723f792 | 0 | pentaho/pentaho-commons-xul | /**
*
*/
package org.pentaho.ui.xul;
import java.beans.PropertyChangeListener;
import org.pentaho.ui.xul.dom.Element;
/**
* The base interface for any XUL widget.
*
* @author nbaker
*
*/
public interface XulComponent extends Element, XulEventSource {
/**
* The manageObject is the rendering control or container that
* corresponds to this XUL component.
* @return the impl control that represents this XUL component under the covers.
*/
public Object getManagedObject();
/**
* The name is the tag name that this component corresponds to
* in XUL XML.
*
* @return the XUL tag name.
*/
public String getName();
/**
* Every element in XUL can have a unique id
* @param id sets the component's id
*/
public void setID(String id);
/**
*
* @return the id for this component.
*/
public String getID();
/**
* Every element in XUL can have a unique id
* @param id sets the component's id
*/
public void setId(String id);
/**
*
* @return the id for this component.
*/
public String getId();
/**
* From the XUL specification: http://www.xulplanet.com/references/elemref/ref_XULElement.html#attr_flex
* Indicates the flexibility of the element, which indicates how an element's
* container distributes remaining empty space among its children. Flexible elements
* grow and shrink to fit their given space. Elements with larger flex values will be
* made larger than elements with lower flex values, at the ratio determined by the two
* elements. The actual value is not relevant unless there are other flexible elements
* within the same container. Once the default sizes of elements in a box are calculated,
* the remaining space in the box is divided among the flexible elements, according to
* their flex ratios.
*
* @return the flex value for this component
*/
public int getFlex();
/**
* This field makes sense only relative to the values of its siblings. NOTE that
* if only one sibling has a flex value, then that sibling gets ALL the
* extra space in the container, no matter what the flex value is.
*
* @param flex
*/
public void setFlex(int flex);
/**
* Sets the method that will be invoked when this component
* loses focus. Also hooks up any listeners for this event.
* @param method the method to execute when the focus is lost.
*/
public void setOnblur(String method);
/**
* Gets the method that will be invoked when this component
* loses focus. Also hooks up any listeners for this event.
*/
public String getOnblur();
/**
* Set the width of this control
*
*/
public void setWidth(int width);
/**
* Returns the width of the component
* @return the component's width
*/
public int getWidth();
/**
* Set the height of the component
*
*/
public void setHeight(int height);
/**
* Returns the height of the component
* @return the component's height
*/
public int getHeight();
public void addPropertyChangeListener(PropertyChangeListener listener);
public void removePropertyChangeListener(PropertyChangeListener listener);
/**
* Sets the enablement state of the component
* @param disabled sets this components enabled state
*
*/
public void setDisabled(boolean disabled);
/**
* XUL's attribute is "disabled", thus this acts
* exactly the opposite of SWT/Swing/AWT. If the property is not
* available, then the control is enabled.
*
* @return boolean true if the control is disabled.
*/
public boolean isDisabled();
public void setTooltiptext(String tooltip);
public String getTooltiptext();
public void setBgcolor(String bgcolor);
public String getBgcolor();
public void setPadding(int padding);
public int getPadding();
public void adoptAttributes(XulComponent component);
public String getInsertbefore();
public void setInsertbefore(String id);
public String getInsertafter();
public void setInsertafter(String id);
public int getPosition();
public void setPosition(int pos);
public boolean getRemoveelement();
public void setRemoveelement(boolean flag);
public boolean isVisible();
public void setVisible(boolean visible);
/**
* Called by the parser when the document is fully parsed. Some implementations require
* knowledge of parents above the document, or only behave properly when an unbroken chain
* to the root is in place.
*/
public void onDomReady();
/**
* Specifies the alignment of children when the size of the container is greater than the
* size of it's children.
*
* @param align one of [start, center, end].
*/
public void setAlign(String align);
/**
* Returns the alignment of children.
*
* @return String specifying the alignment [start, center, end].
*/
public String getAlign();
}
| pentaho-xul-core/src/org/pentaho/ui/xul/XulComponent.java | /**
*
*/
package org.pentaho.ui.xul;
import java.beans.PropertyChangeListener;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.dnd.DragHandler;
import org.pentaho.ui.xul.dnd.DragType;
import org.pentaho.ui.xul.util.Align;
/**
* The base interface for any XUL widget.
*
* @author nbaker
*
*/
public interface XulComponent extends Element, XulEventSource {
/**
* The manageObject is the rendering control or container that
* corresponds to this XUL component.
* @return the impl control that represents this XUL component under the covers.
*/
public Object getManagedObject();
/**
* The name is the tag name that this component corresponds to
* in XUL XML.
*
* @return the XUL tag name.
*/
public String getName();
/**
* Every element in XUL can have a unique id
* @param id sets the component's id
*/
public void setID(String id);
/**
*
* @return the id for this component.
*/
public String getID();
/**
* Every element in XUL can have a unique id
* @param id sets the component's id
*/
public void setId(String id);
/**
*
* @return the id for this component.
*/
public String getId();
/**
* From the XUL specification: http://www.xulplanet.com/references/elemref/ref_XULElement.html#attr_flex
* Indicates the flexibility of the element, which indicates how an element's
* container distributes remaining empty space among its children. Flexible elements
* grow and shrink to fit their given space. Elements with larger flex values will be
* made larger than elements with lower flex values, at the ratio determined by the two
* elements. The actual value is not relevant unless there are other flexible elements
* within the same container. Once the default sizes of elements in a box are calculated,
* the remaining space in the box is divided among the flexible elements, according to
* their flex ratios.
*
* @return the flex value for this component
*/
public int getFlex();
/**
* This field makes sense only relative to the values of its siblings. NOTE that
* if only one sibling has a flex value, then that sibling gets ALL the
* extra space in the container, no matter what the flex value is.
*
* @param flex
*/
public void setFlex(int flex);
/**
* Sets the method that will be invoked when this component
* loses focus. Also hooks up any listeners for this event.
* @param method the method to execute when the focus is lost.
*/
public void setOnblur(String method);
/**
* Gets the method that will be invoked when this component
* loses focus. Also hooks up any listeners for this event.
*/
public String getOnblur();
/**
* Set the width of this control
*
*/
public void setWidth(int width);
/**
* Returns the width of the component
* @return the component's width
*/
public int getWidth();
/**
* Set the height of the component
*
*/
public void setHeight(int height);
/**
* Returns the height of the component
* @return the component's height
*/
public int getHeight();
public void addPropertyChangeListener(PropertyChangeListener listener);
public void removePropertyChangeListener(PropertyChangeListener listener);
/**
* Sets the enablement state of the component
* @param disabled sets this components enabled state
*
*/
public void setDisabled(boolean disabled);
/**
* XUL's attribute is "disabled", thus this acts
* exactly the opposite of SWT/Swing/AWT. If the property is not
* available, then the control is enabled.
*
* @return boolean true if the control is disabled.
*/
public boolean isDisabled();
public void setTooltiptext(String tooltip);
public String getTooltiptext();
public void setBgcolor(String bgcolor);
public String getBgcolor();
public void setPadding(int padding);
public int getPadding();
public void adoptAttributes(XulComponent component);
public String getInsertbefore();
public void setInsertbefore(String id);
public String getInsertafter();
public void setInsertafter(String id);
public int getPosition();
public void setPosition(int pos);
public boolean getRemoveelement();
public void setRemoveelement(boolean flag);
public boolean isVisible();
public void setVisible(boolean visible);
/**
* Called by the parser when the document is fully parsed. Some implementations require
* knowledge of parents above the document, or only behave properly when an unbroken chain
* to the root is in place.
*/
public void onDomReady();
/**
* Specifies the alignment of children when the size of the container is greater than the
* size of it's children.
*
* @param align one of [start, center, end].
*/
public void setAlign(String align);
/**
* Returns the alignment of children.
*
* @return String specifying the alignment [start, center, end].
*/
public String getAlign();
}
| Removed un-used imports causing compilation issues
| pentaho-xul-core/src/org/pentaho/ui/xul/XulComponent.java | Removed un-used imports causing compilation issues |
|
Java | lgpl-2.1 | f9ce9f69394aa39c147997d126a4572f2fcb9bcc | 0 | threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya | //
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.server;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.samskivert.util.IntMap;
import com.samskivert.util.IntMaps;
import com.samskivert.util.LRUHashMap;
import com.samskivert.util.StringUtil;
import com.threerings.io.Streamable;
import com.threerings.presents.client.Client;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.data.InvocationCodes;
import com.threerings.presents.data.InvocationMarshaller;
import com.threerings.presents.data.InvocationMarshaller.ListenerMarshaller;
import com.threerings.presents.dobj.DEvent;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.EventListener;
import com.threerings.presents.dobj.InvocationRequestEvent;
import com.threerings.presents.net.Transport;
import static com.threerings.presents.Log.log;
/**
* The invocation services provide client to server invocations (service requests) and server to
* client invocations (responses and notifications). Via this mechanism, the client can make
* requests of the server, be notified of its response and the server can asynchronously invoke
* code on the client.
*
* <p> Invocations are like remote procedure calls in that they are named and take arguments. All
* arguments must be {@link Streamable} objects, primitive types, or String objects. All arguments
* are passed by value (by serializing and unserializing the arguments); there is no special
* facility provided for referencing non-local objects (it is assumed that the distributed object
* facility will already be in use for any objects that should be shared).
*
* <p> The server invocation manager listens for invocation requests from the client and passes
* them on to the invocation provider registered for the requested invocation module. It also
* provides a mechanism by which responses and asynchronous notification invocations can be
* delivered to the client.
*/
@Singleton
public class InvocationManager
implements EventListener
{
/**
* Constructs an invocation manager which will use the supplied distributed object manager to
* operate its invocation services. Generally only one invocation manager should be operational
* in a particular system.
*/
@Inject public InvocationManager (PresentsDObjectMgr omgr)
{
_omgr = omgr;
_omgr._invmgr = this;
// create the object on which we'll listen for invocation requests
DObject invobj = _omgr.registerObject(new DObject());
invobj.addListener(this);
_invoid = invobj.getOid();
log.debug("Created invocation service object", "oid", _invoid);
}
/**
* Returns the object id of the invocation services object.
*/
public int getOid ()
{
return _invoid;
}
/**
* Registers the supplied invocation service provider.
*
* @param provider the provider to be registered.
* @param mclass the class of the invocation marshaller generated for the service.
*/
public <T extends InvocationMarshaller> T registerProvider (
InvocationProvider provider, Class<T> mclass)
{
return registerProvider(provider, mclass, null);
}
/**
* Registers the supplied invocation service provider.
*
* @param provider the provider to be registered.
* @param mclass the class of the invocation marshaller generated for the service.
* @param group the bootstrap group in which this marshaller is to be registered, or null if it
* is not a bootstrap service. <em>Do not:</em> register a marshaller with multiple boot
* groups. You must collect shared marshaller into as fine grained a set of groups as necessary
* and have different types of clients specify the list of groups they need.
*/
public <T extends InvocationMarshaller> T registerProvider (
final InvocationProvider provider, Class<T> mclass, String group)
{
_omgr.requireEventThread(); // sanity check
// find the invocation provider interface class (defaulting to the concrete class to cope
// with legacy non-interface based providers)
Class<?> pclass = provider.getClass();
String pname = mclass.getSimpleName().replaceAll("Marshaller", "Provider");
OUTER:
for (Class<?> sclass = pclass; sclass != null; sclass = sclass.getSuperclass()) {
for (Class<?> iclass : sclass.getInterfaces()) {
if (InvocationProvider.class.isAssignableFrom(iclass) &&
iclass.getSimpleName().equals(pname)) {
pclass = iclass;
break OUTER;
}
}
}
// determine the invocation service code mappings
final Map<Integer,Method> invmeths = Maps.newHashMap();
for (Method method : pclass.getMethods()) {
Class<?>[] ptypes = method.getParameterTypes();
// only consider methods whose first argument is of type ClientObject; this is a
// non-issue if we are looking at an auto-generated FooProvider interface, but is
// necessary to avoid problems for legacy concrete FooProvider implementations that
// also happen to have overloaded methods with the same name as invocation service
// methods; I'm looking at you ChatProvider...
if (ptypes.length == 0 || !ClientObject.class.isAssignableFrom(ptypes[0])) {
continue;
}
try {
Field code = mclass.getField(StringUtil.unStudlyName(method.getName()));
invmeths.put(code.getInt(null), method);
} catch (IllegalAccessException iae) {
throw new RuntimeException(iae); // Field.get failed? shouldn't happen
} catch (NoSuchFieldException nsfe) {
// not a problem, they just added some extra methods to their provider
}
}
// get the next invocation code
int invCode = nextInvCode();
// create a marshaller instance and initialize it
T marsh;
try {
marsh = mclass.newInstance();
marsh.init(_invoid, invCode, _standaloneClient == null ?
null : _standaloneClient.getInvocationDirector());
} catch (IllegalAccessException ie) {
throw new RuntimeException(ie);
} catch (InstantiationException ie) {
throw new RuntimeException(ie);
}
// register the dispatcher
_dispatchers.put(invCode, new Dispatcher() {
public InvocationProvider getProvider () {
return provider;
}
public void dispatchRequest (ClientObject source, int methodId, Object[] args)
throws InvocationException {
// locate the method to be invoked
Method m = invmeths.get(methodId);
if (m == null) {
String pclass = StringUtil.shortClassName(provider.getClass());
log.warning("Requested to dispatch unknown method", "source", source.who(),
"methodId", methodId, "provider", pclass, "args", args);
throw new InvocationException(InvocationCodes.E_INTERNAL_ERROR);
}
// prepare the arguments: the ClientObject followed by the service method args
Object[] fargs = new Object[args.length+1];
System.arraycopy(args, 0, fargs, 1, args.length);
fargs[0] = source;
// actually invoke the method, and cope with failure
try {
m.invoke(provider, fargs);
} catch (IllegalAccessException ie) {
throw new RuntimeException(ie); // should never happen
} catch (InvocationTargetException ite) {
Throwable cause = ite.getCause();
if (cause instanceof InvocationException) {
throw (InvocationException)cause;
} else {
log.warning("Invocation service method failure",
"provider", StringUtil.shortClassName(provider.getClass()),
"method", m.getName(), "args", fargs, cause);
throw new InvocationException(InvocationCodes.E_INTERNAL_ERROR);
}
}
}
});
// if it's a bootstrap service, slap it in the list
if (group != null) {
_bootlists.put(group, marsh);
}
_recentRegServices.put(Integer.valueOf(invCode), marsh.getClass().getName());
log.debug("Registered service", "code", invCode, "marsh", marsh);
return marsh;
}
/**
* Registers the supplied invocation dispatcher, returning a marshaller that can be used to
* send requests to the provider for whom the dispatcher is proxying.
*
* @param dispatcher the dispatcher to be registered.
*/
public <T extends InvocationMarshaller> T registerDispatcher (
InvocationDispatcher<T> dispatcher)
{
return registerDispatcher(dispatcher, null);
}
/**
* @Deprecated use {@link #registerDispatcher(InvocationDispatcher)}.
*/
public <T extends InvocationMarshaller> T registerDispatcher (
InvocationDispatcher<T> dispatcher, boolean bootstrap)
{
return registerDispatcher(dispatcher, null);
}
/**
* Registers the supplied invocation dispatcher, returning a marshaller that can be used to
* send requests to the provider for whom the dispatcher is proxying.
*
* @param dispatcher the dispatcher to be registered.
* @param group the bootstrap group in which this marshaller is to be registered, or null if it
* is not a bootstrap service. <em>Do not:</em> register a dispatcher with multiple boot
* groups. You must collect shared dispatchers into as fine grained a set of groups as
* necessary and have different types of clients specify the list of groups they need.
*/
public <T extends InvocationMarshaller> T registerDispatcher (
InvocationDispatcher<T> dispatcher, String group)
{
_omgr.requireEventThread(); // sanity check
// get the next invocation code
int invCode = nextInvCode();
// create the marshaller and initialize it
T marsh = dispatcher.createMarshaller();
marsh.init(_invoid, invCode, _standaloneClient == null ?
null : _standaloneClient.getInvocationDirector());
// register the dispatcher
_dispatchers.put(invCode, dispatcher);
// if it's a bootstrap service, slap it in the list
if (group != null) {
_bootlists.put(group, marsh);
}
_recentRegServices.put(Integer.valueOf(invCode), marsh.getClass().getName());
log.debug("Registered service", "code", invCode, "marsh", marsh);
return marsh;
}
/**
* Clears out a dispatcher registration. This should be called to free up resources when an
* invocation service is no longer going to be used.
*/
public void clearDispatcher (InvocationMarshaller marsh)
{
_omgr.requireEventThread(); // sanity check
if (marsh == null) {
log.warning("Refusing to unregister null marshaller.", new Exception());
return;
}
if (_dispatchers.remove(marsh.getInvocationCode()) == null) {
log.warning("Requested to remove unregistered marshaller?", "marsh", marsh,
new Exception());
}
}
/**
* Constructs a list of all bootstrap services registered in any of the supplied groups.
*/
public List<InvocationMarshaller> getBootstrapServices (String[] bootGroups)
{
List<InvocationMarshaller> services = Lists.newArrayList();
for (String group : bootGroups) {
services.addAll(_bootlists.get(group));
}
return services;
}
/**
* Get the class that is being used to dispatch the specified invocation code, for
* informational purposes.
*
* @return the Class, or null if no dispatcher is registered with
* the specified code.
*/
public Class<?> getDispatcherClass (int invCode)
{
Object dispatcher = _dispatchers.get(invCode);
return (dispatcher == null) ? null : dispatcher.getClass();
}
// documentation inherited from interface
public void eventReceived (DEvent event)
{
log.debug("Event received", "event", event);
if (event instanceof InvocationRequestEvent) {
InvocationRequestEvent ire = (InvocationRequestEvent)event;
dispatchRequest(ire.getSourceOid(), ire.getInvCode(),
ire.getMethodId(), ire.getArgs(), ire.getTransport());
}
}
/**
* Called when we receive an invocation request message. Dispatches the request to the
* appropriate invocation provider via the registered invocation dispatcher.
*/
protected void dispatchRequest (
int clientOid, int invCode, int methodId, Object[] args, Transport transport)
{
// make sure the client is still around
ClientObject source = (ClientObject)_omgr.getObject(clientOid);
if (source == null) {
log.info("Client no longer around for invocation request", "clientOid", clientOid,
"code", invCode, "methId", methodId, "args", args);
return;
}
// look up the dispatcher
Dispatcher disp = _dispatchers.get(invCode);
if (disp == null) {
log.info("Received invocation request but dispatcher registration was already cleared",
"code", invCode, "methId", methodId, "args", args,
"marsh", _recentRegServices.get(Integer.valueOf(invCode)));
return;
}
// scan the args, initializing any listeners and keeping track of the "primary" listener
ListenerMarshaller rlist = null;
int acount = args.length;
for (int ii = 0; ii < acount; ii++) {
Object arg = args[ii];
if (arg instanceof ListenerMarshaller) {
ListenerMarshaller list = (ListenerMarshaller)arg;
list.callerOid = clientOid;
list.omgr = _omgr;
list.transport = transport;
// keep track of the listener we'll inform if anything
// goes horribly awry
if (rlist == null) {
rlist = list;
}
}
}
log.debug("Dispatching invreq", "caller", source.who(), "provider", disp.getProvider(),
"methId", methodId, "args", args);
// dispatch the request
try {
if (rlist != null) {
rlist.setInvocationId(StringUtil.shortClassName(disp) + ", methodId=" + methodId);
}
disp.dispatchRequest(source, methodId, args);
} catch (InvocationException ie) {
if (rlist != null) {
rlist.requestFailed(ie.getMessage());
} else {
log.warning("Service request failed but we've got no listener to inform of " +
"the failure", "caller", source.who(), "code", invCode,
"provider", disp.getProvider(), "methodId", methodId, "args", args,
"error", ie);
}
} catch (Throwable t) {
log.warning("Dispatcher choked", "provider", disp.getProvider(), "caller", source.who(),
"methId", methodId, "args", args, t);
// avoid logging an error when the listener notices that it's been ignored.
if (rlist != null) {
rlist.setNoResponse();
}
}
}
/**
* Used to generate monotonically increasing provider ids.
*/
protected synchronized int nextInvCode ()
{
return _invCode++;
}
protected interface Dispatcher {
public InvocationProvider getProvider ();
public void dispatchRequest (ClientObject source, int methodId, Object[] args)
throws InvocationException;
}
/** The object id of the object on which we receive invocation service requests. */
protected int _invoid = -1;
/** Used to generate monotonically increasing provider ids. */
protected int _invCode;
/** A reference to the standalone client, if any. */
@Inject(optional=true) protected Client _standaloneClient;
/** The distributed object manager we're working with. */
protected PresentsDObjectMgr _omgr;
/** A table of invocation dispatchers each mapped by a unique code. */
protected IntMap<Dispatcher> _dispatchers = IntMaps.newHashIntMap();
/** Maps bootstrap group to lists of services to be provided to clients at boot time. */
protected Multimap<String, InvocationMarshaller> _bootlists = ArrayListMultimap.create();
/** Tracks recently registered services so that we can complain informatively if a request
* comes in on a service we don't know about. */
protected final Map<Integer, String> _recentRegServices =
new LRUHashMap<Integer, String>(10000);
/** The text appended to the procedure name when generating a failure response. */
protected static final String FAILED_SUFFIX = "Failed";
}
| src/main/java/com/threerings/presents/server/InvocationManager.java | //
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.server;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.samskivert.util.IntMap;
import com.samskivert.util.IntMaps;
import com.samskivert.util.LRUHashMap;
import com.samskivert.util.StringUtil;
import com.threerings.io.Streamable;
import com.threerings.presents.client.InvocationDirector;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.data.InvocationCodes;
import com.threerings.presents.data.InvocationMarshaller;
import com.threerings.presents.data.InvocationMarshaller.ListenerMarshaller;
import com.threerings.presents.dobj.DEvent;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.EventListener;
import com.threerings.presents.dobj.InvocationRequestEvent;
import com.threerings.presents.net.Transport;
import static com.threerings.presents.Log.log;
/**
* The invocation services provide client to server invocations (service requests) and server to
* client invocations (responses and notifications). Via this mechanism, the client can make
* requests of the server, be notified of its response and the server can asynchronously invoke
* code on the client.
*
* <p> Invocations are like remote procedure calls in that they are named and take arguments. All
* arguments must be {@link Streamable} objects, primitive types, or String objects. All arguments
* are passed by value (by serializing and unserializing the arguments); there is no special
* facility provided for referencing non-local objects (it is assumed that the distributed object
* facility will already be in use for any objects that should be shared).
*
* <p> The server invocation manager listens for invocation requests from the client and passes
* them on to the invocation provider registered for the requested invocation module. It also
* provides a mechanism by which responses and asynchronous notification invocations can be
* delivered to the client.
*/
@Singleton
public class InvocationManager
implements EventListener
{
/**
* Constructs an invocation manager which will use the supplied distributed object manager to
* operate its invocation services. Generally only one invocation manager should be operational
* in a particular system.
*/
@Inject public InvocationManager (PresentsDObjectMgr omgr)
{
_omgr = omgr;
_omgr._invmgr = this;
// create the object on which we'll listen for invocation requests
DObject invobj = _omgr.registerObject(new DObject());
invobj.addListener(this);
_invoid = invobj.getOid();
log.debug("Created invocation service object", "oid", _invoid);
}
/**
* Sets the invocation director to install in created marshallers. This is used in standalone
* mode, where marshallers are not streamed (usually, the director reference is set on
* unstreaming).
*/
public void setInvocationDirector (InvocationDirector invdir)
{
// TODO: change references in existing marshallers?
_invdir = invdir;
}
/**
* Returns the object id of the invocation services object.
*/
public int getOid ()
{
return _invoid;
}
/**
* Registers the supplied invocation service provider.
*
* @param provider the provider to be registered.
* @param mclass the class of the invocation marshaller generated for the service.
*/
public <T extends InvocationMarshaller> T registerProvider (
InvocationProvider provider, Class<T> mclass)
{
return registerProvider(provider, mclass, null);
}
/**
* Registers the supplied invocation service provider.
*
* @param provider the provider to be registered.
* @param mclass the class of the invocation marshaller generated for the service.
* @param group the bootstrap group in which this marshaller is to be registered, or null if it
* is not a bootstrap service. <em>Do not:</em> register a marshaller with multiple boot
* groups. You must collect shared marshaller into as fine grained a set of groups as necessary
* and have different types of clients specify the list of groups they need.
*/
public <T extends InvocationMarshaller> T registerProvider (
final InvocationProvider provider, Class<T> mclass, String group)
{
_omgr.requireEventThread(); // sanity check
// find the invocation provider interface class (defaulting to the concrete class to cope
// with legacy non-interface based providers)
Class<?> pclass = provider.getClass();
String pname = mclass.getSimpleName().replaceAll("Marshaller", "Provider");
OUTER:
for (Class<?> sclass = pclass; sclass != null; sclass = sclass.getSuperclass()) {
for (Class<?> iclass : sclass.getInterfaces()) {
if (InvocationProvider.class.isAssignableFrom(iclass) &&
iclass.getSimpleName().equals(pname)) {
pclass = iclass;
break OUTER;
}
}
}
// determine the invocation service code mappings
final Map<Integer,Method> invmeths = Maps.newHashMap();
for (Method method : pclass.getMethods()) {
Class<?>[] ptypes = method.getParameterTypes();
// only consider methods whose first argument is of type ClientObject; this is a
// non-issue if we are looking at an auto-generated FooProvider interface, but is
// necessary to avoid problems for legacy concrete FooProvider implementations that
// also happen to have overloaded methods with the same name as invocation service
// methods; I'm looking at you ChatProvider...
if (ptypes.length == 0 || !ClientObject.class.isAssignableFrom(ptypes[0])) {
continue;
}
try {
Field code = mclass.getField(StringUtil.unStudlyName(method.getName()));
invmeths.put(code.getInt(null), method);
} catch (IllegalAccessException iae) {
throw new RuntimeException(iae); // Field.get failed? shouldn't happen
} catch (NoSuchFieldException nsfe) {
// not a problem, they just added some extra methods to their provider
}
}
// get the next invocation code
int invCode = nextInvCode();
// create a marshaller instance and initialize it
T marsh;
try {
marsh = mclass.newInstance();
marsh.init(_invoid, invCode, _invdir);
} catch (IllegalAccessException ie) {
throw new RuntimeException(ie);
} catch (InstantiationException ie) {
throw new RuntimeException(ie);
}
// register the dispatcher
_dispatchers.put(invCode, new Dispatcher() {
public InvocationProvider getProvider () {
return provider;
}
public void dispatchRequest (ClientObject source, int methodId, Object[] args)
throws InvocationException {
// locate the method to be invoked
Method m = invmeths.get(methodId);
if (m == null) {
String pclass = StringUtil.shortClassName(provider.getClass());
log.warning("Requested to dispatch unknown method", "source", source.who(),
"methodId", methodId, "provider", pclass, "args", args);
throw new InvocationException(InvocationCodes.E_INTERNAL_ERROR);
}
// prepare the arguments: the ClientObject followed by the service method args
Object[] fargs = new Object[args.length+1];
System.arraycopy(args, 0, fargs, 1, args.length);
fargs[0] = source;
// actually invoke the method, and cope with failure
try {
m.invoke(provider, fargs);
} catch (IllegalAccessException ie) {
throw new RuntimeException(ie); // should never happen
} catch (InvocationTargetException ite) {
Throwable cause = ite.getCause();
if (cause instanceof InvocationException) {
throw (InvocationException)cause;
} else {
log.warning("Invocation service method failure",
"provider", StringUtil.shortClassName(provider.getClass()),
"method", m.getName(), "args", fargs, cause);
throw new InvocationException(InvocationCodes.E_INTERNAL_ERROR);
}
}
}
});
// if it's a bootstrap service, slap it in the list
if (group != null) {
_bootlists.put(group, marsh);
}
_recentRegServices.put(Integer.valueOf(invCode), marsh.getClass().getName());
log.debug("Registered service", "code", invCode, "marsh", marsh);
return marsh;
}
/**
* Registers the supplied invocation dispatcher, returning a marshaller that can be used to
* send requests to the provider for whom the dispatcher is proxying.
*
* @param dispatcher the dispatcher to be registered.
*/
public <T extends InvocationMarshaller> T registerDispatcher (
InvocationDispatcher<T> dispatcher)
{
return registerDispatcher(dispatcher, null);
}
/**
* @Deprecated use {@link #registerDispatcher(InvocationDispatcher)}.
*/
public <T extends InvocationMarshaller> T registerDispatcher (
InvocationDispatcher<T> dispatcher, boolean bootstrap)
{
return registerDispatcher(dispatcher, null);
}
/**
* Registers the supplied invocation dispatcher, returning a marshaller that can be used to
* send requests to the provider for whom the dispatcher is proxying.
*
* @param dispatcher the dispatcher to be registered.
* @param group the bootstrap group in which this marshaller is to be registered, or null if it
* is not a bootstrap service. <em>Do not:</em> register a dispatcher with multiple boot
* groups. You must collect shared dispatchers into as fine grained a set of groups as
* necessary and have different types of clients specify the list of groups they need.
*/
public <T extends InvocationMarshaller> T registerDispatcher (
InvocationDispatcher<T> dispatcher, String group)
{
_omgr.requireEventThread(); // sanity check
// get the next invocation code
int invCode = nextInvCode();
// create the marshaller and initialize it
T marsh = dispatcher.createMarshaller();
marsh.init(_invoid, invCode, _invdir);
// register the dispatcher
_dispatchers.put(invCode, dispatcher);
// if it's a bootstrap service, slap it in the list
if (group != null) {
_bootlists.put(group, marsh);
}
_recentRegServices.put(Integer.valueOf(invCode), marsh.getClass().getName());
log.debug("Registered service", "code", invCode, "marsh", marsh);
return marsh;
}
/**
* Clears out a dispatcher registration. This should be called to free up resources when an
* invocation service is no longer going to be used.
*/
public void clearDispatcher (InvocationMarshaller marsh)
{
_omgr.requireEventThread(); // sanity check
if (marsh == null) {
log.warning("Refusing to unregister null marshaller.", new Exception());
return;
}
if (_dispatchers.remove(marsh.getInvocationCode()) == null) {
log.warning("Requested to remove unregistered marshaller?", "marsh", marsh,
new Exception());
}
}
/**
* Constructs a list of all bootstrap services registered in any of the supplied groups.
*/
public List<InvocationMarshaller> getBootstrapServices (String[] bootGroups)
{
List<InvocationMarshaller> services = Lists.newArrayList();
for (String group : bootGroups) {
services.addAll(_bootlists.get(group));
}
return services;
}
/**
* Get the class that is being used to dispatch the specified invocation code, for
* informational purposes.
*
* @return the Class, or null if no dispatcher is registered with
* the specified code.
*/
public Class<?> getDispatcherClass (int invCode)
{
Object dispatcher = _dispatchers.get(invCode);
return (dispatcher == null) ? null : dispatcher.getClass();
}
// documentation inherited from interface
public void eventReceived (DEvent event)
{
log.debug("Event received", "event", event);
if (event instanceof InvocationRequestEvent) {
InvocationRequestEvent ire = (InvocationRequestEvent)event;
dispatchRequest(ire.getSourceOid(), ire.getInvCode(),
ire.getMethodId(), ire.getArgs(), ire.getTransport());
}
}
/**
* Called when we receive an invocation request message. Dispatches the request to the
* appropriate invocation provider via the registered invocation dispatcher.
*/
protected void dispatchRequest (
int clientOid, int invCode, int methodId, Object[] args, Transport transport)
{
// make sure the client is still around
ClientObject source = (ClientObject)_omgr.getObject(clientOid);
if (source == null) {
log.info("Client no longer around for invocation request", "clientOid", clientOid,
"code", invCode, "methId", methodId, "args", args);
return;
}
// look up the dispatcher
Dispatcher disp = _dispatchers.get(invCode);
if (disp == null) {
log.info("Received invocation request but dispatcher registration was already cleared",
"code", invCode, "methId", methodId, "args", args,
"marsh", _recentRegServices.get(Integer.valueOf(invCode)));
return;
}
// scan the args, initializing any listeners and keeping track of the "primary" listener
ListenerMarshaller rlist = null;
int acount = args.length;
for (int ii = 0; ii < acount; ii++) {
Object arg = args[ii];
if (arg instanceof ListenerMarshaller) {
ListenerMarshaller list = (ListenerMarshaller)arg;
list.callerOid = clientOid;
list.omgr = _omgr;
list.transport = transport;
// keep track of the listener we'll inform if anything
// goes horribly awry
if (rlist == null) {
rlist = list;
}
}
}
log.debug("Dispatching invreq", "caller", source.who(), "provider", disp.getProvider(),
"methId", methodId, "args", args);
// dispatch the request
try {
if (rlist != null) {
rlist.setInvocationId(StringUtil.shortClassName(disp) + ", methodId=" + methodId);
}
disp.dispatchRequest(source, methodId, args);
} catch (InvocationException ie) {
if (rlist != null) {
rlist.requestFailed(ie.getMessage());
} else {
log.warning("Service request failed but we've got no listener to inform of " +
"the failure", "caller", source.who(), "code", invCode,
"provider", disp.getProvider(), "methodId", methodId, "args", args,
"error", ie);
}
} catch (Throwable t) {
log.warning("Dispatcher choked", "provider", disp.getProvider(), "caller", source.who(),
"methId", methodId, "args", args, t);
// avoid logging an error when the listener notices that it's been ignored.
if (rlist != null) {
rlist.setNoResponse();
}
}
}
/**
* Used to generate monotonically increasing provider ids.
*/
protected synchronized int nextInvCode ()
{
return _invCode++;
}
protected interface Dispatcher {
public InvocationProvider getProvider ();
public void dispatchRequest (ClientObject source, int methodId, Object[] args)
throws InvocationException;
}
/** The object id of the object on which we receive invocation service requests. */
protected int _invoid = -1;
/** Used to generate monotonically increasing provider ids. */
protected int _invCode;
/** The invocation director reference to install in created marshallers (if any). */
protected InvocationDirector _invdir;
/** The distributed object manager we're working with. */
protected PresentsDObjectMgr _omgr;
/** A table of invocation dispatchers each mapped by a unique code. */
protected IntMap<Dispatcher> _dispatchers = IntMaps.newHashIntMap();
/** Maps bootstrap group to lists of services to be provided to clients at boot time. */
protected Multimap<String, InvocationMarshaller> _bootlists = ArrayListMultimap.create();
/** Tracks recently registered services so that we can complain informatively if a request
* comes in on a service we don't know about. */
protected final Map<Integer, String> _recentRegServices =
new LRUHashMap<Integer, String>(10000);
/** The text appended to the procedure name when generating a failure response. */
protected static final String FAILED_SUFFIX = "Failed";
}
| On second thought, let's configure the standalone client reference via an
optional injection.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@6414 542714f4-19e9-0310-aa3c-eee0fc999fb1
| src/main/java/com/threerings/presents/server/InvocationManager.java | On second thought, let's configure the standalone client reference via an optional injection. |
|
Java | unlicense | a83fcc954b93295e16b07c6c0f482541f2b0270a | 0 | rednoah/keydial | package ntu.csie.keydial;
import java.io.FileInputStream;
import java.io.InputStream;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.RotateEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Watch watch = new Watch();
watch.setLayoutX(15);
watch.setLayoutY(20);
stage.setScene(new Scene(watch, Color.TRANSPARENT));
stage.initStyle(StageStyle.TRANSPARENT);
stage.show();
// touch input
stage.getScene().setOnRotate(new EventHandler<RotateEvent>() {
double sum = 0, speed = 0.5;
@Override
public void handle(RotateEvent evt) {
sum += speed * evt.getAngle();
if (sum < -1) {
watch.left();
sum = 0;
}
if (sum > +1) {
watch.right();
sum = 0;
}
}
});
// mouse input
stage.getScene().setOnMouseClicked((evt) -> {
if (evt.getButton() == MouseButton.PRIMARY)
watch.enter();
if (evt.getButton() == MouseButton.SECONDARY)
watch.select();
});
stage.getScene().setOnScroll((evt) -> {
if (evt.getDeltaY() < 0)
watch.left();
if (evt.getDeltaY() > 0)
watch.right();
});
// keyboard input
stage.getScene().setOnKeyPressed((evt) -> {
switch (evt.getCode()) {
case SPACE:
watch.enter();
break;
case RIGHT:
watch.right();
break;
case LEFT:
watch.left();
break;
case DOWN:
watch.select();
break;
default:
break;
}
});
Thread eventReader = new Thread(() -> {
try (InputStream in = getSerialInputStream()) {
int b = 0;
while ((b = in.read()) > 0) {
final KeyCode code = b == 'L' ? KeyCode.LEFT : b == 'R' ? KeyCode.RIGHT : b == '*' ? KeyCode.DOWN : KeyCode.SPACE;
Platform.runLater(() -> {
stage.getScene().getOnKeyPressed().handle(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", code, false, false, false, false));
});
}
} catch (Exception e) {
e.printStackTrace();
}
});
eventReader.start();
}
static InputStream getSerialInputStream() throws Exception {
return new FileInputStream("serial.txt");
}
}
| src/ntu/csie/keydial/Main.java | package ntu.csie.keydial;
import java.io.FileInputStream;
import java.io.InputStream;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Watch watch = new Watch();
watch.setLayoutX(15);
watch.setLayoutY(20);
stage.setScene(new Scene(watch, Color.TRANSPARENT));
stage.initStyle(StageStyle.TRANSPARENT);
stage.show();
stage.getScene().setOnKeyPressed((evt) -> {
switch (evt.getCode()) {
case SPACE:
watch.enter();
break;
case RIGHT:
watch.right();
break;
case LEFT:
watch.left();
break;
case DOWN:
watch.select();
break;
default:
break;
}
});
Thread eventReader = new Thread(() -> {
try (InputStream in = getSerialInputStream()) {
int b = 0;
while ((b = in.read()) > 0) {
final KeyCode code = b == 'L' ? KeyCode.LEFT : b == 'R' ? KeyCode.RIGHT : b == '*' ? KeyCode.DOWN : KeyCode.SPACE;
Platform.runLater(() -> {
stage.getScene().getOnKeyPressed().handle(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", code, false, false, false, false));
});
}
} catch (Exception e) {
e.printStackTrace();
}
});
eventReader.start();
}
static InputStream getSerialInputStream() throws Exception {
return new FileInputStream("serial.txt");
}
}
| * try different input methods
| src/ntu/csie/keydial/Main.java | * try different input methods |
|
Java | apache-2.0 | cdb64cedcb7af3fa91521d2fb8d5a5a113242232 | 0 | rozza/mongo-java-driver,kevinsawicki/mongo-java-driver,davydotcom/mongo-java-driver,wanggc/mongo-java-driver,davydotcom/mongo-java-driver,jyemin/mongo-java-driver,kevinsawicki/mongo-java-driver,kevinsawicki/mongo-java-driver,kay-kim/mongo-java-driver,jyemin/mongo-java-driver,gianpaj/mongo-java-driver,jsonking/mongo-java-driver,PSCGroup/mongo-java-driver,jsonking/mongo-java-driver,wanggc/mongo-java-driver,rozza/mongo-java-driver | // Mongo.java
/**
* Copyright (C) 2008 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import org.bson.io.*;
/**
* A database connection with internal pooling.
* For most application, you should have 1 Mongo instance for the entire JVM.
*
* The following are equivalent, and all connect to the
* local database running on the default port:
*
* <blockquote><pre>
* Mongo mongo1 = new Mongo( "127.0.0.1" );
* Mongo mongo2 = new Mongo( "127.0.0.1", 27017 );
* Mongo mongo3 = new Mongo( new DBAddress( "127.0.0.1:27017", "test" ) )
* </pre></blockquote>
*
* Mongo instances have connection pooling built in - see the requestStart
* and requestDone methods for more information.
* http://www.mongodb.org/display/DOCS/Java+Driver+Concurrency
*
* <h3>Connecting to a Replica Pair</h3>
* <p>
* You can connect to a
* <a href="http://www.mongodb.org/display/DOCS/Replica+Pairs">replica pair</a>
* using the Java driver by passing two DBAddresses to the Mongo constructor.
* For example:
* </p>
* <blockquote><pre>
* DBAddress left = new DBAddress("localhost:27017/test");
* DBAddress right = new DBAddress("localhost:27018/test");
*
* Mongo mongo = new Mongo(left, right);
* </pre></blockquote>
*
* <p>
* If the master of a replica pair goes down, there will be a brief lag before
* the slave becomes master. Thus, your application should be prepared to catch
* the exceptions that might be thrown in such a case: IllegalArgumentException,
* MongoException, and MongoException.Network (depending on when the connection
* drops).
* </p>
* <p>
* Once the slave becomes master, the driver will begin using that connection
* as the master connection and the exceptions will stop being thrown.
* </p>
*/
public class Mongo {
public static final int MAJOR_VERSION = 2;
public static final int MINOR_VERSION = 2;
public static DB connect( DBAddress addr ){
return new Mongo( addr ).getDB( addr.getDBName() );
}
public Mongo()
throws UnknownHostException , MongoException {
this( new ServerAddress() );
}
/**
* Connects to a (single) mongodb node (default port)
*
* @param host server to connect to
* @throws UnknownHostException if the database host cannot be resolved
*/
public Mongo( String host )
throws UnknownHostException , MongoException {
this( new ServerAddress( host ) );
}
/**
* Connects to a (single) mongodb node (default port)
* @param host server to connect to
* @param options options to use
* @throws UnknownHostException if the database host cannot be resolved
*/
public Mongo( String host , MongoOptions options )
throws UnknownHostException , MongoException {
this( new ServerAddress( host ) , options );
}
/**
* Connects to a (single) mongodb node
* @param host the database's host address
* @param port the port on which the database is running
* @throws UnknownHostException if the database host cannot be resolved
*/
public Mongo( String host , int port )
throws UnknownHostException , MongoException {
this( new ServerAddress( host , port ) );
}
/**
* Connects to a (single) mongodb node
* @see com.mongodb.ServerAddress
* @param addr the database address
*/
public Mongo( ServerAddress addr )
throws MongoException {
this( addr , new MongoOptions() );
}
/**
* Connects to a (single) mongo node using a given ServerAddress
* @see com.mongodb.ServerAddress
* @param addr the database address
*/
public Mongo( ServerAddress addr , MongoOptions options )
throws MongoException {
_addr = addr;
_addrs = null;
_options = options;
_connector = new DBTCPConnector( this , _addr );
_connector.checkMaster( true , true );
_connector.testMaster();
}
/**
* <p>Creates a Mongo connection in paired mode. <br/> This will also work for
* a replica set and will find all members (the master will be used by
* default).</p>
*
* @see com.mongodb.ServerAddress
* @param left left side of the pair
* @param right right side of the pair
*/
public Mongo( ServerAddress left , ServerAddress right )
throws MongoException {
this( left , right , new MongoOptions() );
}
/**
* <p>Creates a Mongo connection in paired mode. <br/> This will also work for
* a replica set and will find all members (the master will be used by
* default).</p>
*
* @see com.mongodb.ServerAddress
* @param left left side of the pair
* @param right right side of the pair
*/
public Mongo( ServerAddress left , ServerAddress right , MongoOptions options )
throws MongoException {
_addr = null;
_addrs = Arrays.asList( left , right );
_options = options;
_connector = new DBTCPConnector( this , _addrs );
_connector.checkMaster( true , false );
_connector.testMaster();
}
/**
* <p>Creates a Mongo connection. <br/> This will work for
* a replica set, or pair, and will find all members (the master will be used by
* default).</p>
*
* @see com.mongodb.ServerAddress
* @pair replicaSetSeeds put as many servers as you can in the list.
* the system will figure the rest out
*/
public Mongo( List<ServerAddress> replicaSetSeeds )
throws MongoException {
this( replicaSetSeeds , new MongoOptions() );
}
/**
* <p>Creates a Mongo connection. <br/> This will work for
* a replica set, or pair, and will find all members (the master will be used by
* default).</p>
*
* @see com.mongodb.ServerAddress
* @param replicaSetSeeds put as many servers as you can in the list.
* the system will figure the rest out
*/
public Mongo( List<ServerAddress> replicaSetSeeds , MongoOptions options )
throws MongoException {
_addr = null;
_addrs = replicaSetSeeds;
_options = options;
_connector = new DBTCPConnector( this , _addrs );
_connector.checkMaster( true , false );
}
/**
* Creates a Mongo connection. If only one address is used it will only connect to that node, otherwise it will discover all nodes.
* @see MongoURI
* <p>examples:
* <li>mongodb://localhost</li>
* <li>mongodb://fred:foobar@localhost/</li>
* </p>
* @dochub connections
*/
public Mongo( MongoURI uri )
throws MongoException , UnknownHostException {
_options = uri.getOptions();
if ( uri.getHosts().size() == 1 ){
_addr = new ServerAddress( uri.getHosts().get(0) );
_addrs = null;
_connector = new DBTCPConnector( this , _addr );
_connector.testMaster();
}
else {
List<ServerAddress> replicaSetSeeds = new ArrayList<ServerAddress>( uri.getHosts().size() );
for ( String host : uri.getHosts() )
replicaSetSeeds.add( new ServerAddress( host ) );
_addr = null;
_addrs = replicaSetSeeds;
_connector = new DBTCPConnector( this , replicaSetSeeds );
_connector.checkMaster( true , true );
}
}
public DB getDB( String dbname ){
DB db = _dbs.get( dbname );
if ( db != null )
return db;
db = new DBApiLayer( this , dbname , _connector );
DB temp = _dbs.putIfAbsent( dbname , db );
if ( temp != null )
return temp;
return db;
}
public List<String> getDatabaseNames()
throws MongoException {
BasicDBObject cmd = new BasicDBObject();
cmd.put("listDatabases", 1);
BasicDBObject res = (BasicDBObject)getDB( "admin" ).command(cmd);
if (res.getInt("ok" , 0 ) != 1 )
throw new MongoException( "error listing databases : " + res );
List l = (List)res.get("databases");
List<String> list = new ArrayList<String>();
for (Object o : l) {
list.add(((BasicDBObject)o).getString("name"));
}
return list;
}
/**
* Drops the database if it exists.
*
* @param dbName name of database to drop
*/
public void dropDatabase(String dbName)
throws MongoException {
getDB( dbName ).dropDatabase();
}
public String getVersion(){
return MAJOR_VERSION + "." + MINOR_VERSION;
}
public String debugString(){
return _connector.debugString();
}
public String getConnectPoint(){
return _connector.getConnectPoint();
}
/** Gets the address of this database.
* @return the address
*/
public ServerAddress getAddress(){
return _connector.getAddress();
}
public List<ServerAddress> getAllAddress() {
List<ServerAddress> result = _connector.getAllAddress();
if (result == null) {
return Arrays.asList(getAddress());
}
return result;
}
/**
* closes all open connections
* this Mongo cannot be re-used
*/
public void close(){
_connector.close();
}
/**
* Set the write concern for this database. Will be used for
* writes to any collection in this database. See the
* documentation for {@link WriteConcern} for more information.
*
* @param concern write concern to use
*/
public void setWriteConcern( WriteConcern concern ){
_concern = concern;
}
/**
* Get the write concern for this database.
*/
public WriteConcern getWriteConcern(){
return _concern;
}
/**
* makes this query ok to run on a slave node
*/
public void slaveOk(){
addOption( Bytes.QUERYOPTION_SLAVEOK );
}
public void addOption( int option ){
_netOptions.add( option );
}
public void setOptions( int options ){
_netOptions.set( options );
}
public void resetOptions(){
_netOptions.reset();
}
public int getOptions(){
return _netOptions.get();
}
final ServerAddress _addr;
final List<ServerAddress> _addrs;
final MongoOptions _options;
final DBTCPConnector _connector;
final ConcurrentMap<String,DB> _dbs = new ConcurrentHashMap<String,DB>();
private WriteConcern _concern = WriteConcern.NORMAL;
final Bytes.OptionHolder _netOptions = new Bytes.OptionHolder( null );
org.bson.util.SimplePool<PoolOutputBuffer> _bufferPool =
new org.bson.util.SimplePool<PoolOutputBuffer>( 1000 ){
protected PoolOutputBuffer createNew(){
return new PoolOutputBuffer();
}
};
// -------
/**
* Mongo.Holder is if you want to have a static place to hold instances of Mongo
* security is not enforced at this level, so need to do on your side
*/
public static class Holder {
public Mongo connect( MongoURI uri )
throws MongoException , UnknownHostException {
String key = _toKey( uri );
Mongo m = _mongos.get(key);
if ( m != null )
return m;
m = new Mongo( uri );
Mongo temp = _mongos.putIfAbsent( key , m );
if ( temp == null ){
// ours got in
return m;
}
// there was a race and we lost
// close ours and return the other one
m.close();
return temp;
}
String _toKey( MongoURI uri ){
StringBuilder buf = new StringBuilder();
for ( String h : uri.getHosts() )
buf.append( h ).append( "," );
buf.append( uri.getOptions() );
buf.append( uri.getUsername() );
return buf.toString();
}
private static final ConcurrentMap<String,Mongo> _mongos = new ConcurrentHashMap<String,Mongo>();
}
}
| src/main/com/mongodb/Mongo.java | // Mongo.java
/**
* Copyright (C) 2008 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import org.bson.io.*;
/**
* A database connection with internal pooling.
* For most application, you should have 1 Mongo instance for the entire JVM.
*
* The following are equivalent, and all connect to the
* local database running on the default port:
*
* <blockquote><pre>
* Mongo mongo1 = new Mongo( "127.0.0.1" );
* Mongo mongo2 = new Mongo( "127.0.0.1", 27017 );
* Mongo mongo3 = new Mongo( new DBAddress( "127.0.0.1:27017", "test" ) )
* </pre></blockquote>
*
* Mongo instances have connection pooling built in - see the requestStart
* and requestDone methods for more information.
* http://www.mongodb.org/display/DOCS/Java+Driver+Concurrency
*
* <h3>Connecting to a Replica Pair</h3>
* <p>
* You can connect to a
* <a href="http://www.mongodb.org/display/DOCS/Replica+Pairs">replica pair</a>
* using the Java driver by passing two DBAddresses to the Mongo constructor.
* For example:
* </p>
* <blockquote><pre>
* DBAddress left = new DBAddress("localhost:27017/test");
* DBAddress right = new DBAddress("localhost:27018/test");
*
* Mongo mongo = new Mongo(left, right);
* </pre></blockquote>
*
* <p>
* If the master of a replica pair goes down, there will be a brief lag before
* the slave becomes master. Thus, your application should be prepared to catch
* the exceptions that might be thrown in such a case: IllegalArgumentException,
* MongoException, and MongoException.Network (depending on when the connection
* drops).
* </p>
* <p>
* Once the slave becomes master, the driver will begin using that connection
* as the master connection and the exceptions will stop being thrown.
* </p>
*/
public class Mongo {
public static final int MAJOR_VERSION = 2;
public static final int MINOR_VERSION = 2;
public static DB connect( DBAddress addr ){
return new Mongo( addr ).getDB( addr.getDBName() );
}
public Mongo()
throws UnknownHostException , MongoException {
this( new ServerAddress() );
}
/**
* Connects to the local mongo instance on default port.
*
* @param host server to connect to
* @throws UnknownHostException if the database host cannot be resolved
*/
public Mongo( String host )
throws UnknownHostException , MongoException {
this( new ServerAddress( host ) );
}
/**
* Connects to the local mongo instance on default port.
*
* @param host server to connect to
* @param options options to use
* @throws UnknownHostException if the database host cannot be resolved
*/
public Mongo( String host , MongoOptions options )
throws UnknownHostException , MongoException {
this( new ServerAddress( host ) , options );
}
/**
* Connects to Mongo using a given host, port, and database.
* @param host the database's host address
* @param port the port on which the database is running
* @throws UnknownHostException if the database host cannot be resolved
*/
public Mongo( String host , int port )
throws UnknownHostException , MongoException {
this( new ServerAddress( host , port ) );
}
/**
* Connects to Mongo using a given DBAddress
* @see com.mongodb.DBAddress
* @param addr the database address
*/
public Mongo( ServerAddress addr )
throws MongoException {
this( addr , new MongoOptions() );
}
/**
* Connects to Mongo using a given DBAddress
* @see com.mongodb.DBAddress
* @param addr the database address
*/
public Mongo( ServerAddress addr , MongoOptions options )
throws MongoException {
_addr = addr;
_addrs = null;
_options = options;
_connector = new DBTCPConnector( this , _addr );
_connector.checkMaster( true , true );
_connector.testMaster();
}
/**
creates a Mongo connection in paired mode
* @param left left side of the pair
* @param right right side of the pair
*/
public Mongo( ServerAddress left , ServerAddress right )
throws MongoException {
this( left , right , new MongoOptions() );
}
/**
creates a Mongo connection in paired mode
* @param left left side of the pair
* @param right right side of the pair
*/
public Mongo( ServerAddress left , ServerAddress right , MongoOptions options )
throws MongoException {
_addr = null;
_addrs = Arrays.asList( left , right );
_options = options;
_connector = new DBTCPConnector( this , _addrs );
_connector.checkMaster( true , false );
_connector.testMaster();
}
/**
* creates a Mongo connection to a replica set
* @pair replicaSetSeeds put as many servers as you can in the list.
* the system will figure the rest out
*/
public Mongo( List<ServerAddress> replicaSetSeeds )
throws MongoException {
this( replicaSetSeeds , new MongoOptions() );
}
/**
* creates a Mongo connection to a replica set
* @pair replicaSetSeeds put as many servers as you can in the list.
* the system will figure the rest out
*/
public Mongo( List<ServerAddress> replicaSetSeeds , MongoOptions options )
throws MongoException {
_addr = null;
_addrs = replicaSetSeeds;
_options = options;
_connector = new DBTCPConnector( this , _addrs );
_connector.checkMaster( true , false );
}
public Mongo( MongoURI uri )
throws MongoException , UnknownHostException {
_options = uri.getOptions();
if ( uri.getHosts().size() == 1 ){
_addr = new ServerAddress( uri.getHosts().get(0) );
_addrs = null;
_connector = new DBTCPConnector( this , _addr );
_connector.testMaster();
}
else {
List<ServerAddress> replicaSetSeeds = new ArrayList<ServerAddress>( uri.getHosts().size() );
for ( String host : uri.getHosts() )
replicaSetSeeds.add( new ServerAddress( host ) );
_addr = null;
_addrs = replicaSetSeeds;
_connector = new DBTCPConnector( this , replicaSetSeeds );
_connector.checkMaster( true , true );
}
}
public DB getDB( String dbname ){
DB db = _dbs.get( dbname );
if ( db != null )
return db;
db = new DBApiLayer( this , dbname , _connector );
DB temp = _dbs.putIfAbsent( dbname , db );
if ( temp != null )
return temp;
return db;
}
public List<String> getDatabaseNames()
throws MongoException {
BasicDBObject cmd = new BasicDBObject();
cmd.put("listDatabases", 1);
BasicDBObject res = (BasicDBObject)getDB( "admin" ).command(cmd);
if (res.getInt("ok" , 0 ) != 1 )
throw new MongoException( "error listing databases : " + res );
List l = (List)res.get("databases");
List<String> list = new ArrayList<String>();
for (Object o : l) {
list.add(((BasicDBObject)o).getString("name"));
}
return list;
}
/**
* Drops the database if it exists.
*
* @param dbName name of database to drop
*/
public void dropDatabase(String dbName)
throws MongoException {
getDB( dbName ).dropDatabase();
}
public String getVersion(){
return MAJOR_VERSION + "." + MINOR_VERSION;
}
public String debugString(){
return _connector.debugString();
}
public String getConnectPoint(){
return _connector.getConnectPoint();
}
/** Gets the address of this database.
* @return the address
*/
public ServerAddress getAddress(){
return _connector.getAddress();
}
public List<ServerAddress> getAllAddress() {
List<ServerAddress> result = _connector.getAllAddress();
if (result == null) {
return Arrays.asList(getAddress());
}
return result;
}
/**
* closes all open connections
* this Mongo cannot be re-used
*/
public void close(){
_connector.close();
}
/**
* Set the write concern for this database. Will be used for
* writes to any collection in this database. See the
* documentation for {@link WriteConcern} for more information.
*
* @param concern write concern to use
*/
public void setWriteConcern( WriteConcern concern ){
_concern = concern;
}
/**
* Get the write concern for this database.
*/
public WriteConcern getWriteConcern(){
return _concern;
}
/**
* makes this query ok to run on a slave node
*/
public void slaveOk(){
addOption( Bytes.QUERYOPTION_SLAVEOK );
}
public void addOption( int option ){
_netOptions.add( option );
}
public void setOptions( int options ){
_netOptions.set( options );
}
public void resetOptions(){
_netOptions.reset();
}
public int getOptions(){
return _netOptions.get();
}
final ServerAddress _addr;
final List<ServerAddress> _addrs;
final MongoOptions _options;
final DBTCPConnector _connector;
final ConcurrentMap<String,DB> _dbs = new ConcurrentHashMap<String,DB>();
private WriteConcern _concern = WriteConcern.NORMAL;
final Bytes.OptionHolder _netOptions = new Bytes.OptionHolder( null );
org.bson.util.SimplePool<PoolOutputBuffer> _bufferPool =
new org.bson.util.SimplePool<PoolOutputBuffer>( 1000 ){
protected PoolOutputBuffer createNew(){
return new PoolOutputBuffer();
}
};
// -------
/**
* Mongo.Holder is if you want to have a static place to hold instances of Mongo
* security is not enforced at this level, so need to do on your side
*/
public static class Holder {
public Mongo connect( MongoURI uri )
throws MongoException , UnknownHostException {
String key = _toKey( uri );
Mongo m = _mongos.get(key);
if ( m != null )
return m;
m = new Mongo( uri );
Mongo temp = _mongos.putIfAbsent( key , m );
if ( temp == null ){
// ours got in
return m;
}
// there was a race and we lost
// close ours and return the other one
m.close();
return temp;
}
String _toKey( MongoURI uri ){
StringBuilder buf = new StringBuilder();
for ( String h : uri.getHosts() )
buf.append( h ).append( "," );
buf.append( uri.getOptions() );
buf.append( uri.getUsername() );
return buf.toString();
}
private static final ConcurrentMap<String,Mongo> _mongos = new ConcurrentHashMap<String,Mongo>();
}
}
| updated mongo constructor javadocs
| src/main/com/mongodb/Mongo.java | updated mongo constructor javadocs |
|
Java | apache-2.0 | d164b5ef1c3d3e2e6978d0c3144a07886a195866 | 0 | LTT-Gatech/CarCareAndroid | package com.teamltt.carcare.activity;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import com.github.pires.obd.commands.ObdCommand;
import com.github.pires.obd.commands.SpeedCommand;
import com.github.pires.obd.commands.engine.RuntimeCommand;
import com.teamltt.carcare.adapter.IObdSocket;
import com.teamltt.carcare.adapter.bluetooth.DeviceSocket;
import com.teamltt.carcare.database.DbHelper;
import com.teamltt.carcare.database.contract.ResponseContract;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* Any Activity can start this service to request for the bluetooth to start logging OBD data to the database
*/
public class ObdBluetoothService extends Service {
private static final String TAG = "ObdBluetoothService";
// Text that appears in the phone's bluetooth manager for the adapter
private final String OBDII_NAME = "OBDII";
// UUID that is required to talk to the OBD II adapter
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothDevice obdDevice = null;
private BluetoothAdapter bluetoothAdapter;
private IObdSocket socket;
/**
* A writable database connection
*/
private SQLiteDatabase db;
/**
* Used to catch bluetooth status related events.
* Relies on the Android Manifest including android.bluetooth.adapter.action.STATE_CHANGED in a receiver tag
*/
BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "bt state receiver " + action);
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
switch (state){
case BluetoothAdapter.STATE_ON:
//Indicates the local Bluetooth adapter is on, and ready for use.
getObdDevice();
break;
}
}
}
};
/**
* Used to catch bluetooth discovery related events.
*/
BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "discovery receiver " + action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i(TAG, "potential device found");
Log.i(TAG, device.toString());
if (device.getName() != null && device.getName().equals(OBDII_NAME)) {
Log.i(TAG, "desired device found");
obdDevice = device;
obdDeviceObtained();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.i(TAG, "discovery unsuccessful");
// UI message connectButton.setText(R.string.retry_connect);
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.i(TAG, "discovery started");
}
}
};
/**
* Activities wanting to use this service will register with it instead of binding, but in the absence of all
* activities, data should still be logged.
*
*/
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("This Service does not support binding.");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "service started");
// Register the BroadcastReceiver
IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
discoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryReceiver, discoveryFilter);
IntentFilter bluetoothFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(bluetoothReceiver, bluetoothFilter);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
// Do not try to connect if the device is already trying to or if our socket is open
if (!bluetoothAdapter.isEnabled()) {
Log.i(TAG, "requesting to enable BT");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
enableBtIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Gives the user a chance to reject Bluetooth privileges at this time
startActivity(enableBtIntent);
// goes to onActivityResult where requestCode == REQUEST_ENABLE_BT
}
else {
Log.i(TAG, "adapter enabled");
// If bluetooth is on, go ahead and use it
getObdDevice();
}
} // Else does not support Bluetooth
// START_NOT_STICKY means when the service is stopped/killed, do NOT automatically restart the service
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
// release resources
unregisterReceiver(discoveryReceiver);
unregisterReceiver(bluetoothReceiver);
Log.i(TAG, "service stopped");
}
/**
* Returns a cached bluetooth device named OBDII_NAME or starts a discovery and bonds with a device like that.
*/
private void getObdDevice() {
// Query pair
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals(OBDII_NAME)) {
obdDevice = device;
break;
}
}
}
if (obdDevice != null) {
/* TODO a cached pair for device named "OBDII_NAME" is found if you have connected successfully. But what if
you try using a new adapter with a new MAC address - this will need to be discovered */
Log.i(TAG, "existing pair found");
obdDeviceObtained();
} else {
Log.i(TAG, "starting discovery");
if (bluetoothAdapter.startDiscovery()) {
// Control goes to bluetoothReceiver member variable
Log.i(TAG, "discovery started");
// UI message connectButton.setText(R.string.discovering);
} else {
Log.i(TAG, "discovery not started");
// UI message connectButton.setText(R.string.permission_fail_bt);
}
}
}
private void obdDeviceObtained() {
Log.i(TAG, "trying socket creation");
try {
socket = new DeviceSocket(obdDevice.createRfcommSocketToServiceRecord(uuid));
// UI message connectButton.setText(R.string.connecting_bt);
connectTask.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This task takes control of the device's bluetooth and opens a socket to the OBD adapter.
*/
AsyncTask<Void, Void, Void> connectTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
// Android advises to cancel discovery before using socket.connect()
if (bluetoothAdapter.cancelDiscovery()) {
// connect if discovery successfully canceled
socket.connect();
} else {
Log.e(TAG, "could not cancel discovery");
}
// Connect to the database
db = new DbHelper(ObdBluetoothService.this).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Add user feedback with Messenger and Handler
queryTask.execute();
}
};
/**
* This task checks periodically if the car is on, then starts cycling through commands that CarCare tracks and
* storing them in the database.
*/
AsyncTask<Void, Void, Void> queryTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... ignore) {
try {
while (socket.isConnected()) {
// Check for can's "heartbeat"
ObdCommand heartbeat = new RuntimeCommand();
while (true) {
heartbeat.run(socket.getInputStream(), socket.getOutputStream());
if (Integer.parseInt(heartbeat.getFormattedResult()) > 0) {
break;
}
}
// TODO establish a new trip_id here
Set<Class<? extends ObdCommand>> commands = new HashSet<>();
// TODO get these classes from somewhere else
commands.add(RuntimeCommand.class);
commands.add(SpeedCommand.class);
for (Class<? extends ObdCommand> commandClass : commands) {
ObdCommand sendCommand = commandClass.newInstance();
if (!socket.isConnected()) {
// In case the Bluetooth connection breaks suddenly
break;
} else {
sendCommand.run(socket.getInputStream(), socket.getOutputStream());
}
// Add this response to the database
ContentValues values = new ContentValues();
values.put(ResponseContract.ResponseEntry.COLUMN_NAME_TRIP_ID, 0);
values.put(ResponseContract.ResponseEntry.COLUMN_NAME_NAME, sendCommand.getName());
values.put(ResponseContract.ResponseEntry.COLUMN_NAME_PID, sendCommand.getCommandPID());
values.put(ResponseContract.ResponseEntry.COLUMN_NAME_VALUE, sendCommand.getFormattedResult());
db.insert(ResponseContract.ResponseEntry.TABLE_NAME, null, values);
}
}
} catch (IOException | InterruptedException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void ignore) {
// TODO Tell the user the socket was disconnected or there was another exception
// Also give them a way to reconnect it
}
};
}
| app/src/main/java/com/teamltt/carcare/activity/ObdBluetoothService.java | package com.teamltt.carcare.activity;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import com.github.pires.obd.commands.ObdCommand;
import com.github.pires.obd.commands.SpeedCommand;
import com.github.pires.obd.commands.engine.RuntimeCommand;
import com.teamltt.carcare.adapter.IObdSocket;
import com.teamltt.carcare.adapter.bluetooth.DeviceSocket;
import com.teamltt.carcare.database.DbHelper;
import com.teamltt.carcare.database.contract.ResponseContract;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* Any Activity can start this service to request for the bluetooth to start logging OBD data to the database
*/
public class ObdBluetoothService extends Service {
private static final String TAG = "ObdBluetoothService";
// Text that appears in the phone's bluetooth manager for the adapter
private final String OBDII_NAME = "OBDII";
// UUID that is required to talk to the OBD II adapter
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothDevice obdDevice = null;
private BluetoothAdapter bluetoothAdapter;
private IObdSocket socket;
/**
* A writable database connection
*/
private SQLiteDatabase db;
/**
* Used to catch bluetooth status related events.
* Relies on the Android Manifest including android.bluetooth.adapter.action.STATE_CHANGED in a receiver tag
*/
BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "bt state receiver " + action);
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
switch (state){
case BluetoothAdapter.STATE_ON:
//Indicates the local Bluetooth adapter is on, and ready for use.
getObdDevice();
break;
}
}
}
};
/**
* Used to catch bluetooth discovery related events.
*/
BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "discovery receiver " + action);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i(TAG, "potential device found");
Log.i(TAG, device.toString());
if (device.getName() != null && device.getName().equals(OBDII_NAME)) {
Log.i(TAG, "desired device found");
obdDevice = device;
obdDeviceObtained();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.i(TAG, "discovery unsuccessful");
// UI message connectButton.setText(R.string.retry_connect);
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.i(TAG, "discovery started");
}
}
};
/**
* Activities wanting to use this service will register with it instead of binding, but in the absence of all
* activities, data should still be logged.
*
*/
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("This Service does not support binding.");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "service started");
// Register the BroadcastReceiver
IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
discoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryReceiver, discoveryFilter);
IntentFilter bluetoothFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(bluetoothReceiver, bluetoothFilter);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
// Do not try to connect if the device is already trying to or if our socket is open
if (!bluetoothAdapter.isEnabled()) {
Log.i(TAG, "requesting to enable BT");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
enableBtIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Gives the user a chance to reject Bluetooth privileges at this time
startActivity(enableBtIntent);
// goes to onActivityResult where requestCode == REQUEST_ENABLE_BT
}
else {
Log.i(TAG, "adapter enabled");
// If bluetooth is on, go ahead and use it
getObdDevice();
}
} // Else does not support Bluetooth
// START_NOT_STICKY means when the service is stopped/killed, do NOT automatically restart the service
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
// release resources
unregisterReceiver(discoveryReceiver);
unregisterReceiver(bluetoothReceiver);
Log.i(TAG, "service stopped");
}
/**
* Returns a cached bluetooth device named OBDII_NAME or starts a discovery and bonds with a device like that.
*/
private void getObdDevice() {
// Query pair
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals(OBDII_NAME)) {
obdDevice = device;
break;
}
}
}
if (obdDevice != null) {
/* TODO a cached pair for device named "OBDII_NAME" is found if you have connected successfully. But what if
you try using a new adapter with a new MAC address - this will need to be discovered */
Log.i(TAG, "existing pair found");
obdDeviceObtained();
} else {
Log.i(TAG, "starting discovery");
if (bluetoothAdapter.startDiscovery()) {
// Control goes to bluetoothReceiver member variable
Log.i(TAG, "discovery started");
// UI message connectButton.setText(R.string.discovering);
} else {
Log.i(TAG, "discovery not started");
// UI message connectButton.setText(R.string.permission_fail_bt);
}
}
}
private void obdDeviceObtained() {
Log.i(TAG, "trying socket creation");
try {
socket = new DeviceSocket(obdDevice.createRfcommSocketToServiceRecord(uuid));
// UI message connectButton.setText(R.string.connecting_bt);
connectTask.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This task takes control of the device's bluetooth and opens a socket to the OBD adapter.
*/
AsyncTask<Void, Void, Void> connectTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
// Android advises to cancel discovery before using socket.connect()
if (bluetoothAdapter.cancelDiscovery()) {
// connect if discovery successfully canceled
socket.connect();
} else {
Log.e(TAG, "discovery unable to cancel");
}
// Connect to the database
db = new DbHelper(ObdBluetoothService.this).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Add user feedback with Messenger and Handler
queryTask.execute();
}
};
/**
* This task checks periodically if the car is on, then starts cycling through commands that CarCare tracks and
* storing them in the database.
*/
AsyncTask<Void, Void, Void> queryTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... ignore) {
try {
while (socket.isConnected()) {
// Check for can's "heartbeat"
boolean isCarOn = false;
while (!isCarOn) {
ObdCommand heartbeat = new RuntimeCommand();
heartbeat.run(socket.getInputStream(), socket.getOutputStream());
if (Integer.parseInt(heartbeat.getFormattedResult()) > 0) {
isCarOn = true;
}
}
Set<Class<? extends ObdCommand>> commands = new HashSet<>();
// TODO get these classes from somewhere else
commands.add(RuntimeCommand.class);
commands.add(SpeedCommand.class);
for (Class<? extends ObdCommand> commandClass : commands) {
ObdCommand sendCommand = commandClass.newInstance();
if (!socket.isConnected()) {
// In case the Bluetooth connection breaks suddenly
break;
} else {
sendCommand.run(socket.getInputStream(), socket.getOutputStream());
}
// Add this response to the database
ContentValues values = new ContentValues();
// TODO trip_id logic?
values.put(ResponseContract.ResponseEntry.COLUMN_NAME_TRIP_ID, 0);
values.put(ResponseContract.ResponseEntry.COLUMN_NAME_NAME, sendCommand.getName());
values.put(ResponseContract.ResponseEntry.COLUMN_NAME_PID, sendCommand.getCommandPID());
values.put(ResponseContract.ResponseEntry.COLUMN_NAME_VALUE, sendCommand.getFormattedResult());
db.insert(ResponseContract.ResponseEntry.TABLE_NAME, null, values);
}
}
} catch (IOException | InterruptedException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void ignore) {
// TODO Tell the user the socket was disconnected or there was another exception
// Also give them a way to reconnect it
}
};
}
| Clarified a log
Removed unnecessary class constructions
| app/src/main/java/com/teamltt/carcare/activity/ObdBluetoothService.java | Clarified a log Removed unnecessary class constructions |
|
Java | apache-2.0 | 7d500de34bd7b7c20e717fd53bf58518329500cd | 0 | hobermallow/LogAnalizer | package it.uniroma1.lcl.dietrolequinte.loader.query;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import it.uniroma1.lcl.dietrolequinte.Utente;
import it.uniroma1.lcl.dietrolequinte.loader.AbstractLoader;
/**
* Classe che implementa il Loader per i file log di tipo query, per il motore di
* ricerca AOL
*
* @author Andrea
*
*/
public class QueryLoader extends AbstractLoader {
public QueryLoader(File file) throws IOException {
super(file);
}
/* (non-Javadoc)
* @see it.uniroma1.lcl.dietrolequinte.loader.AbstractLoader#getListValidSearch()
*/
@Override
protected List<String> getListValidSearch() {
return Arrays.asList("interrogazione");
}
/* (non-Javadoc)
* @see it.uniroma1.lcl.dietrolequinte.loader.AbstractLoader#inizializzaLoader(java.util.List)
*/
@Override
protected void inizializzaLoader(List<String> list) {
list.remove(0);
list.stream().filter(s -> s != null).map(s -> Arrays.asList(s.split("\t"))).forEach(this::analizzaRiga);
}
/* (non-Javadoc)
* @see it.uniroma1.lcl.dietrolequinte.loader.AbstractLoader#analizzaRiga(java.util.List)
*/
@Override
protected void analizzaRiga(List<String> riga) {
if(riga.size() == 5) {
addInterrogazione(new Interrogazione(new Utente(riga.get(0)), riga.get(1), LocalDateTime.parse(riga.get(2).replace(" ", "T"), DateTimeFormatter.ISO_LOCAL_DATE_TIME) , riga.get(4), Integer.valueOf(riga.get(3))));
}
else if(riga.size() == 3) {
addInterrogazione(new Interrogazione(new Utente(riga.get(0)), riga.get(1), LocalDateTime.parse(riga.get(2).replace(" ", "T"), DateTimeFormatter.ISO_LOCAL_DATE_TIME)));
}
addUtente(new Utente(riga.get(0)));
}
}
| src/it/uniroma1/lcl/dietrolequinte/loader/query/QueryLoader.java | package it.uniroma1.lcl.dietrolequinte.loader.query;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import it.uniroma1.lcl.dietrolequinte.Utente;
import it.uniroma1.lcl.dietrolequinte.loader.AbstractLoader;
public class QueryLoader extends AbstractLoader {
public QueryLoader(File file) throws IOException {
super(file);
}
@Override
protected List<String> getListValidSearch() {
return Arrays.asList("interrogazione");
}
@Override
protected void inizializzaLoader(List<String> list) {
list.remove(0);
list.stream().filter(s -> s != null).map(s -> Arrays.asList(s.split("\t"))).forEach(this::analizzaRiga);
}
@Override
protected void analizzaRiga(List<String> riga) {
if(riga.size() == 5) {
addInterrogazione(new Interrogazione(new Utente(riga.get(0)), riga.get(1), LocalDateTime.parse(riga.get(2).replace(" ", "T"), DateTimeFormatter.ISO_LOCAL_DATE_TIME) , riga.get(4), Integer.valueOf(riga.get(3))));
}
else if(riga.size() == 3) {
addInterrogazione(new Interrogazione(new Utente(riga.get(0)), riga.get(1), LocalDateTime.parse(riga.get(2).replace(" ", "T"), DateTimeFormatter.ISO_LOCAL_DATE_TIME)));
}
addUtente(new Utente(riga.get(0)));
}
public static void main(String[] args) throws IOException {
File f = new File("/home/onoda/Documents/progetto_metodologie2015/AOL/query.user-ct-test-collection-03.txt.gz");
QueryLoader ql = new QueryLoader(f);
System.out.println(ql);
}
}
| javadoc
| src/it/uniroma1/lcl/dietrolequinte/loader/query/QueryLoader.java | javadoc |
|
Java | apache-2.0 | 184c50a29008f3f952eadc86210a8ba7d6433f1f | 0 | JinWenQiang/FloodlightController,omkale/myfloodlight,xph906/SDN-NW,ZhangMenghao/Floodlight,alsmadi/CSCI-6617,TKTL-SDN/SoftOffload-Master,geddings/floodlight,phisolani/floodlight,srcvirus/floodlight,xuraylei/floodlight,dhruvkakadiya/FloodlightLoadBalancer,andiwundsam/floodlight-sync-proto,xph906/SDN,dhruvkakadiya/FloodlightLoadBalancer,netgroup/floodlight,m1k3lin0/SDNProject,daniel666/multicastSDN,SujithPandel/floodlight,thisthat/floodlight-controller,jmiserez/floodlight,drinkwithwater/floodlightplus,alberthitanaya/floodlight-dnscollector,xph906/SDN,niuqg/floodlight-test,marcbaetica/Floodlight-OVS-OF-Network-Solution-,fazevedo86/floodlight,fazevedo86/floodlight,marymiller/floodlight,rsharo/floodlight,pixuan/floodlight,yeasy/floodlight-lc,teja-/floodlight,avbleverik/floodlight,JinWenQiang/FloodlightController,baykovr/floodlight,rhoybeen/floodlightLB,cbarrin/EAGERFloodlight,rcchan/cs168-sdn-floodlight,pablotiburcio/AutoManIoT,onebsv1/floodlightworkbench,UdS-TelecommunicationsLab/floodlight,srcvirus/floodlight,hgupta2/floodlight2,Pengfei-Lu/floodlight,iluckydonkey/floodlight,rizard/SOSForFloodlight,duanjp8617/floodlight,CS-6617-Java/Floodlight,avbleverik/floodlight,cbarrin/EAGERFloodlight,phisolani/floodlight,andi-bigswitch/floodlight-oss,duanjp8617/floodlight,ZhangMenghao/Floodlight,aprakash6/floodlight_video_cacher,AndreMantas/floodlight,xph906/SDN-ec2,alexreimers/floodlight,xph906/SDN-ec2,baykovr/floodlight,swiatecki/DTUSDN,rizard/geni-cinema,pixuan/floodlight,onebsv1/floodlight,marcbaetica/Floodlight-OVS-OF-Network-Solution-,UdS-TelecommunicationsLab/floodlight,thisthat/floodlight-controller,marymiller/floodlight,thisthat/floodlight-controller,rizard/fast-failover-demo,moisesber/floodlight,TKTL-SDN/SoftOffload-Master,chinmaymhatre91/floodlight,alsmadi/CSCI-6617,m1k3lin0/SDNProject,niuqg/floodlight-test,09zwcbupt/floodlight,wallnerryan/FL_HAND,jmiserez/floodlight,alexreimers/floodlight,chechoRP/floodlight,marymiller/floodlight,xph906/SDN-ec2,thisthat/floodlight-controller,UdS-TelecommunicationsLab/floodlight,deepurple/floodlight,SujithPandel/floodlight,chinmaymhatre91/floodlight,UdS-TelecommunicationsLab/floodlight,xuraylei/floodlight,TKTL-SDN/SoftOffload-Master,iluckydonkey/floodlight,marymiller/floodlight,rizard/floodlight,alberthitanaya/floodlight-dnscollector,swiatecki/DTUSDN,netgroup/floodlight,CS-6617-Java/Floodlight,alexreimers/floodlight,Pengfei-Lu/floodlight,woniu17/floodlight,andi-bigswitch/floodlight-oss,smartnetworks/floodlight,rizard/floodlight,rizard/fast-failover-demo,cbarrin/EAGERFloodlight,rcchan/cs168-sdn-floodlight,ZhangMenghao/Floodlight,xph906/SDN-NW,netgroup/floodlight,floodlight/floodlight,aprakash6/floodlight_video_cacher,TidyHuang/floodlight,duanjp8617/floodlight,srcvirus/floodlight,xph906/SDN,rhoybeen/floodlightLB,drinkwithwater/floodlightplus,omkale/myfloodlight,xph906/SDN-NW,m1k3lin0/SDNProject,alexreimers/floodlight,pablotiburcio/AutoManIoT,aprakash6/floodlight_video_cacher,rhoybeen/floodlightLB,baykovr/floodlight,CS-6617-Java/Floodlight,TKTL-SDN/SoftOffload-Master,rizard/fast-failover-demo,netgroup/floodlight,smartnetworks/floodlight,UdS-TelecommunicationsLab/floodlight,niuqg/floodlight-test,deepurple/floodlight,thisthat/floodlight-controller,pixuan/floodlight,AndreMantas/floodlight,chinmaymhatre91/floodlight,swiatecki/DTUSDN,phisolani/floodlight,drinkwithwater/floodlightplus,deepurple/floodlight,omkale/myfloodlight,smartnetworks/floodlight,CS-6617-Java/Floodlight,andi-bigswitch/floodlight-oss,AndreMantas/floodlight,xph906/SDN,chechoRP/floodlight,aprakash6/floodlight_video_cacher,chinmaymhatre91/floodlight,m1k3lin0/SDNProject,rizard/SOSForFloodlight,moisesber/floodlight,fazevedo86/floodlight,CS-6617-Java/Floodlight,TidyHuang/floodlight,09zwcbupt/floodlight,alsmadi/CSCI-6617,aprakash6/floodlight_video_cacher,dhruvkakadiya/FloodlightLoadBalancer,alsmadi/CSCI-6617,dhruvkakadiya/FloodlightLoadBalancer,iluckydonkey/floodlight,SujithPandel/floodlight,hgupta2/floodlight2,CS-6617-Java/Floodlight,Pengfei-Lu/floodlight,dhruvkakadiya/FloodlightLoadBalancer,rhoybeen/floodlightLB,CS-6617-Java/Floodlight,yeasy/floodlight-lc,baykovr/floodlight,teja-/floodlight,niuqg/floodlight-test,JinWenQiang/FloodlightController,onebsv1/floodlightworkbench,TidyHuang/floodlight,moisesber/floodlight,pablotiburcio/AutoManIoT,deepurple/floodlight,09zwcbupt/floodlight,Linerd/sdn_optimization,SujithPandel/floodlight,Pengfei-Lu/floodlight,marcbaetica/Floodlight-OVS-OF-Network-Solution-,wallnerryan/FL_HAND,moisesber/floodlight,hgupta2/floodlight2,TKTL-SDN/SoftOffload-Master,drinkwithwater/floodlightplus,jmiserez/floodlight,xph906/SDN-NW,rizard/geni-cinema,Pengfei-Lu/floodlight,rizard/geni-cinema,alsmadi/CSCI-6617,JinWenQiang/FloodlightController,netgroup/floodlight,daniel666/multicastSDN,floodlight/floodlight,smartnetworks/floodlight,alberthitanaya/floodlight-dnscollector,Linerd/sdn_optimization,chechoRP/floodlight,JinWenQiang/FloodlightController,ZhangMenghao/Floodlight,phisolani/floodlight,rizard/fast-failover-demo,rsharo/floodlight,kvm2116/floodlight,ZhangMenghao/Floodlight,yeasy/floodlight-lc,yeasy/floodlight-lc,alberthitanaya/floodlight-dnscollector,09zwcbupt/floodlight,kvm2116/floodlight,avbleverik/floodlight,woniu17/floodlight,teja-/floodlight,xuraylei/floodlight,moisesber/floodlight,geddings/floodlight,iluckydonkey/floodlight,rizard/fast-failover-demo,rhoybeen/floodlightLB,xph906/SDN,alexreimers/floodlight,rizard/floodlight,daniel666/multicastSDN,andiwundsam/floodlight-sync-proto,rcchan/cs168-sdn-floodlight,rcchan/cs168-sdn-floodlight,srcvirus/floodlight,smartnetworks/floodlight,duanjp8617/floodlight,avbleverik/floodlight,rcchan/cs168-sdn-floodlight,rizard/geni-cinema,woniu17/floodlight,xph906/SDN-NW,deepurple/floodlight,pixuan/floodlight,xph906/SDN-ec2,pixuan/floodlight,avbleverik/floodlight,fazevedo86/floodlight,TidyHuang/floodlight,Linerd/sdn_optimization,hgupta2/floodlight2,woniu17/floodlight,rsharo/floodlight,phisolani/floodlight,jmiserez/floodlight,onebsv1/floodlight,geddings/floodlight,xph906/SDN-ec2,rizard/geni-cinema,baykovr/floodlight,chechoRP/floodlight,andi-bigswitch/floodlight-oss,rizard/SOSForFloodlight,onebsv1/floodlightworkbench,kvm2116/floodlight,wallnerryan/FL_HAND,floodlight/floodlight,swiatecki/DTUSDN,onebsv1/floodlight,andiwundsam/floodlight-sync-proto,woniu17/floodlight,teja-/floodlight,alberthitanaya/floodlight-dnscollector,wallnerryan/FL_HAND,fazevedo86/floodlight,TidyHuang/floodlight,swiatecki/DTUSDN,jmiserez/floodlight,andiwundsam/floodlight-sync-proto,marcbaetica/Floodlight-OVS-OF-Network-Solution-,daniel666/multicastSDN,Linerd/sdn_optimization,duanjp8617/floodlight,chinmaymhatre91/floodlight,iluckydonkey/floodlight,chechoRP/floodlight,m1k3lin0/SDNProject | /**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.floodlightcontroller.routing;
import java.io.IOException;
import java.util.EnumSet;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.annotations.LogMessageCategory;
import net.floodlightcontroller.core.annotations.LogMessageDoc;
import net.floodlightcontroller.core.annotations.LogMessageDocs;
import net.floodlightcontroller.core.util.AppCookie;
import net.floodlightcontroller.counter.ICounterStoreService;
import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.devicemanager.IDeviceListener;
import net.floodlightcontroller.devicemanager.IDeviceService;
import net.floodlightcontroller.devicemanager.SwitchPort;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.IPacket;
import net.floodlightcontroller.routing.IRoutingService;
import net.floodlightcontroller.routing.IRoutingDecision;
import net.floodlightcontroller.routing.Route;
import net.floodlightcontroller.topology.ITopologyService;
import net.floodlightcontroller.topology.NodePortTuple;
import net.floodlightcontroller.util.OFMessageDamper;
import net.floodlightcontroller.util.TimedCache;
import org.openflow.protocol.OFFlowMod;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPacketIn;
import org.openflow.protocol.OFPacketOut;
import org.openflow.protocol.OFType;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract base class for implementing a forwarding module. Forwarding is
* responsible for programming flows to a switch in response to a policy
* decision.
*/
@LogMessageCategory("Flow Programming")
public abstract class ForwardingBase
implements IOFMessageListener, IDeviceListener {
protected static Logger log =
LoggerFactory.getLogger(ForwardingBase.class);
protected static int OFMESSAGE_DAMPER_CAPACITY = 10000; // TODO: find sweet spot
protected static int OFMESSAGE_DAMPER_TIMEOUT = 250; // ms
public static short FLOWMOD_DEFAULT_IDLE_TIMEOUT = 5; // in seconds
public static short FLOWMOD_DEFAULT_HARD_TIMEOUT = 0; // infinite
protected IFloodlightProviderService floodlightProvider;
protected IDeviceService deviceManager;
protected IRoutingService routingEngine;
protected ITopologyService topology;
protected ICounterStoreService counterStore;
protected OFMessageDamper messageDamper;
// for broadcast loop suppression
protected boolean broadcastCacheFeature = true;
public final int prime1 = 2633; // for hash calculation
public final static int prime2 = 4357; // for hash calculation
public TimedCache<Long> broadcastCache =
new TimedCache<Long>(100, 5*1000); // 5 seconds interval;
// flow-mod - for use in the cookie
public static final int FORWARDING_APP_ID = 2; // TODO: This must be managed
// by a global APP_ID class
public long appCookie = AppCookie.makeCookie(FORWARDING_APP_ID, 0);
// Comparator for sorting by SwitchCluster
public Comparator<SwitchPort> clusterIdComparator =
new Comparator<SwitchPort>() {
@Override
public int compare(SwitchPort d1, SwitchPort d2) {
Long d1ClusterId =
topology.getL2DomainId(d1.getSwitchDPID());
Long d2ClusterId =
topology.getL2DomainId(d2.getSwitchDPID());
return d1ClusterId.compareTo(d2ClusterId);
}
};
/**
* init data structures
*
*/
protected void init() {
messageDamper = new OFMessageDamper(OFMESSAGE_DAMPER_CAPACITY,
EnumSet.of(OFType.FLOW_MOD),
OFMESSAGE_DAMPER_TIMEOUT);
}
/**
* Adds a listener for devicemanager and registers for PacketIns.
*/
protected void startUp() {
deviceManager.addListener(this);
floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
}
/**
* Returns the application name "forwarding".
*/
@Override
public String getName() {
return "forwarding";
}
/**
* All subclasses must define this function if they want any specific
* forwarding action
*
* @param sw
* Switch that the packet came in from
* @param pi
* The packet that came in
* @param decision
* Any decision made by a policy engine
*/
public abstract Command
processPacketInMessage(IOFSwitch sw, OFPacketIn pi,
IRoutingDecision decision,
FloodlightContext cntx);
@Override
public Command receive(IOFSwitch sw, OFMessage msg,
FloodlightContext cntx) {
switch (msg.getType()) {
case PACKET_IN:
IRoutingDecision decision = null;
if (cntx != null)
decision =
IRoutingDecision.rtStore.get(cntx,
IRoutingDecision.CONTEXT_DECISION);
return this.processPacketInMessage(sw,
(OFPacketIn) msg,
decision,
cntx);
default:
break;
}
return Command.CONTINUE;
}
/**
* Push routes from back to front
* @param route Route to push
* @param match OpenFlow fields to match on
* @param srcSwPort Source switch port for the first hop
* @param dstSwPort Destination switch port for final hop
* @param cookie The cookie to set in each flow_mod
* @param cntx The floodlight context
* @param reqeustFlowRemovedNotifn if set to true then the switch would
* send a flow mod removal notification when the flow mod expires
* @param doFlush if set to true then the flow mod would be immediately
* written to the switch
* @param flowModCommand flow mod. command to use, e.g. OFFlowMod.OFPFC_ADD,
* OFFlowMod.OFPFC_MODIFY etc.
* @return srcSwitchIincluded True if the source switch is included in this route
*/
@LogMessageDocs({
@LogMessageDoc(level="WARN",
message="Unable to push route, switch at DPID {dpid} not available",
explanation="A switch along the calculated path for the " +
"flow has disconnected.",
recommendation=LogMessageDoc.CHECK_SWITCH),
@LogMessageDoc(level="ERROR",
message="Failure writing flow mod",
explanation="An I/O error occurred while writing a " +
"flow modification to a switch",
recommendation=LogMessageDoc.CHECK_SWITCH),
})
public boolean pushRoute(Route route, OFMatch match,
Integer wildcard_hints,
OFPacketIn pi,
long pinSwitch,
long cookie,
FloodlightContext cntx,
boolean reqeustFlowRemovedNotifn,
boolean doFlush,
short flowModCommand) {
boolean srcSwitchIncluded = false;
OFFlowMod fm =
(OFFlowMod) floodlightProvider.getOFMessageFactory()
.getMessage(OFType.FLOW_MOD);
OFActionOutput action = new OFActionOutput();
action.setMaxLength((short)0xffff);
List<OFAction> actions = new ArrayList<OFAction>();
actions.add(action);
fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
.setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
.setBufferId(OFPacketOut.BUFFER_ID_NONE)
.setCookie(cookie)
.setCommand(flowModCommand)
.setMatch(match)
.setActions(actions)
.setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
List<NodePortTuple> switchPortList = route.getPath();
for (int indx = switchPortList.size()-1; indx > 0; indx -= 2) {
// indx and indx-1 will always have the same switch DPID.
long switchDPID = switchPortList.get(indx).getNodeId();
IOFSwitch sw = floodlightProvider.getSwitches().get(switchDPID);
if (sw == null) {
if (log.isWarnEnabled()) {
log.warn("Unable to push route, switch at DPID {} " +
"not available", switchDPID);
}
return srcSwitchIncluded;
}
// set the match.
fm.setMatch(wildcard(match, sw, wildcard_hints));
// set buffer id if it is the source switch
if (1 == indx) {
// Set the flag to request flow-mod removal notifications only for the
// source switch. The removal message is used to maintain the flow
// cache. Don't set the flag for ARP messages - TODO generalize check
if ((reqeustFlowRemovedNotifn)
&& (match.getDataLayerType() != Ethernet.TYPE_ARP)) {
fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM);
match.setWildcards(fm.getMatch().getWildcards());
}
}
short outPort = switchPortList.get(indx).getPortId();
short inPort = switchPortList.get(indx-1).getPortId();
// set input and output ports on the switch
fm.getMatch().setInputPort(inPort);
((OFActionOutput)fm.getActions().get(0)).setPort(outPort);
try {
counterStore.updatePktOutFMCounterStore(sw, fm);
if (log.isTraceEnabled()) {
log.trace("Pushing Route flowmod routeIndx={} " +
"sw={} inPort={} outPort={}",
new Object[] {indx,
sw,
fm.getMatch().getInputPort(),
outPort });
}
messageDamper.write(sw, fm, cntx);
if (doFlush) {
sw.flush();
}
// Push the packet out the source switch
if (sw.getId() == pinSwitch) {
// TODO: Instead of doing a packetOut here we could also
// send a flowMod with bufferId set....
pushPacket(sw, match, pi, outPort, cntx);
srcSwitchIncluded = true;
}
} catch (IOException e) {
log.error("Failure writing flow mod", e);
}
try {
fm = fm.clone();
} catch (CloneNotSupportedException e) {
log.error("Failure cloning flow mod", e);
}
}
return srcSwitchIncluded;
}
protected OFMatch wildcard(OFMatch match, IOFSwitch sw,
Integer wildcard_hints) {
if (wildcard_hints != null) {
return match.clone().setWildcards(wildcard_hints.intValue());
}
return match.clone();
}
/**
* Pushes a packet-out to a switch. If bufferId != BUFFER_ID_NONE we
* assume that the packetOut switch is the same as the packetIn switch
* and we will use the bufferId
* Caller needs to make sure that inPort and outPort differs
* @param packet packet data to send
* @param sw switch from which packet-out is sent
* @param bufferId bufferId
* @param inPort input port
* @param outPort output port
* @param cntx context of the packet
* @param flush force to flush the packet.
*/
@LogMessageDocs({
@LogMessageDoc(level="ERROR",
message="BufferId is not and packet data is null. " +
"Cannot send packetOut. " +
"srcSwitch={dpid} inPort={port} outPort={port}",
explanation="The switch send a malformed packet-in." +
"The packet will be dropped",
recommendation=LogMessageDoc.REPORT_SWITCH_BUG),
@LogMessageDoc(level="ERROR",
message="Failure writing packet out",
explanation="An I/O error occurred while writing a " +
"packet out to a switch",
recommendation=LogMessageDoc.CHECK_SWITCH),
})
public void pushPacket(IPacket packet,
IOFSwitch sw,
int bufferId,
short inPort,
short outPort,
FloodlightContext cntx,
boolean flush) {
if (log.isTraceEnabled()) {
log.trace("PacketOut srcSwitch={} inPort={} outPort={}",
new Object[] {sw, inPort, outPort});
}
OFPacketOut po =
(OFPacketOut) floodlightProvider.getOFMessageFactory()
.getMessage(OFType.PACKET_OUT);
// set actions
List<OFAction> actions = new ArrayList<OFAction>();
actions.add(new OFActionOutput(outPort, (short) 0xffff));
po.setActions(actions)
.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
short poLength =
(short) (po.getActionsLength() + OFPacketOut.MINIMUM_LENGTH);
// set buffer_id, in_port
po.setBufferId(bufferId);
po.setInPort(inPort);
// set data - only if buffer_id == -1
if (po.getBufferId() == OFPacketOut.BUFFER_ID_NONE) {
if (packet == null) {
log.error("BufferId is not set and packet data is null. " +
"Cannot send packetOut. " +
"srcSwitch={} inPort={} outPort={}",
new Object[] {sw, inPort, outPort});
return;
}
byte[] packetData = packet.serialize();
poLength += packetData.length;
po.setPacketData(packetData);
}
po.setLength(poLength);
try {
counterStore.updatePktOutFMCounterStore(sw, po);
messageDamper.write(sw, po, cntx, flush);
} catch (IOException e) {
log.error("Failure writing packet out", e);
}
}
/**
* Pushes a packet-out to a switch. The assumption here is that
* the packet-in was also generated from the same switch. Thus, if the input
* port of the packet-in and the outport are the same, the function will not
* push the packet-out.
* @param sw switch that generated the packet-in, and from which packet-out is sent
* @param match OFmatch
* @param pi packet-in
* @param outport output port
* @param cntx context of the packet
*/
protected void pushPacket(IOFSwitch sw, OFMatch match, OFPacketIn pi,
short outport, FloodlightContext cntx) {
if (pi == null) {
return;
} else if (pi.getInPort() == outport){
log.warn("Packet out not sent as the outport matches inport. {}",
pi);
return;
}
// The assumption here is (sw) is the switch that generated the
// packet-in. If the input port is the same as output port, then
// the packet-out should be ignored.
if (pi.getInPort() == outport) {
if (log.isDebugEnabled()) {
log.debug("Attempting to do packet-out to the same " +
"interface as packet-in. Dropping packet. " +
" SrcSwitch={}, match = {}, pi={}",
new Object[]{sw, match, pi});
return;
}
}
if (log.isTraceEnabled()) {
log.trace("PacketOut srcSwitch={} match={} pi={}",
new Object[] {sw, match, pi});
}
OFPacketOut po =
(OFPacketOut) floodlightProvider.getOFMessageFactory()
.getMessage(OFType.PACKET_OUT);
// set actions
List<OFAction> actions = new ArrayList<OFAction>();
actions.add(new OFActionOutput(outport, (short) 0xffff));
po.setActions(actions)
.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
short poLength =
(short) (po.getActionsLength() + OFPacketOut.MINIMUM_LENGTH);
// If the switch doens't support buffering set the buffer id to be none
// otherwise it'll be the the buffer id of the PacketIn
if (sw.getBuffers() == 0) {
// We set the PI buffer id here so we don't have to check again below
pi.setBufferId(OFPacketOut.BUFFER_ID_NONE);
po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
} else {
po.setBufferId(pi.getBufferId());
}
po.setInPort(pi.getInPort());
// If the buffer id is none or the switch doesn's support buffering
// we send the data with the packet out
if (pi.getBufferId() == OFPacketOut.BUFFER_ID_NONE) {
byte[] packetData = pi.getPacketData();
poLength += packetData.length;
po.setPacketData(packetData);
}
po.setLength(poLength);
try {
counterStore.updatePktOutFMCounterStore(sw, po);
messageDamper.write(sw, po, cntx);
} catch (IOException e) {
log.error("Failure writing packet out", e);
}
}
/**
* Write packetout message to sw with output actions to one or more
* output ports with inPort/outPorts passed in.
* @param packetData
* @param sw
* @param inPort
* @param ports
* @param cntx
*/
public void packetOutMultiPort(byte[] packetData,
IOFSwitch sw,
short inPort,
Set<Integer> outPorts,
FloodlightContext cntx) {
//setting actions
List<OFAction> actions = new ArrayList<OFAction>();
Iterator<Integer> j = outPorts.iterator();
while (j.hasNext())
{
actions.add(new OFActionOutput(j.next().shortValue(),
(short) 0));
}
OFPacketOut po =
(OFPacketOut) floodlightProvider.getOFMessageFactory().
getMessage(OFType.PACKET_OUT);
po.setActions(actions);
po.setActionsLength((short) (OFActionOutput.MINIMUM_LENGTH *
outPorts.size()));
// set buffer-id to BUFFER_ID_NONE, and set in-port to OFPP_NONE
po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
po.setInPort(inPort);
// data (note buffer_id is always BUFFER_ID_NONE) and length
short poLength = (short)(po.getActionsLength() +
OFPacketOut.MINIMUM_LENGTH);
poLength += packetData.length;
po.setPacketData(packetData);
po.setLength(poLength);
try {
counterStore.updatePktOutFMCounterStore(sw, po);
if (log.isTraceEnabled()) {
log.trace("write broadcast packet on switch-id={} " +
"interfaces={} packet-out={}",
new Object[] {sw.getId(), outPorts, po});
}
messageDamper.write(sw, po, cntx);
} catch (IOException e) {
log.error("Failure writing packet out", e);
}
}
/**
* @see packetOutMultiPort
* Accepts a PacketIn instead of raw packet data. Note that the inPort
* and switch can be different than the packet in switch/port
*/
public void packetOutMultiPort(OFPacketIn pi,
IOFSwitch sw,
short inPort,
Set<Integer> outPorts,
FloodlightContext cntx) {
packetOutMultiPort(pi.getPacketData(), sw, inPort, outPorts, cntx);
}
/**
* @see packetOutMultiPort
* Accepts an IPacket instead of raw packet data. Note that the inPort
* and switch can be different than the packet in switch/port
*/
public void packetOutMultiPort(IPacket packet,
IOFSwitch sw,
short inPort,
Set<Integer> outPorts,
FloodlightContext cntx) {
packetOutMultiPort(packet.serialize(), sw, inPort, outPorts, cntx);
}
protected boolean isInBroadcastCache(IOFSwitch sw, OFPacketIn pi,
FloodlightContext cntx) {
// Get the cluster id of the switch.
// Get the hash of the Ethernet packet.
if (sw == null) return true;
// If the feature is disabled, always return false;
if (!broadcastCacheFeature) return false;
Ethernet eth =
IFloodlightProviderService.bcStore.get(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
Long broadcastHash;
broadcastHash = topology.getL2DomainId(sw.getId()) * prime1 +
pi.getInPort() * prime2 + eth.hashCode();
if (broadcastCache.update(broadcastHash)) {
sw.updateBroadcastCache(broadcastHash, pi.getInPort());
return true;
} else {
return false;
}
}
protected boolean isInSwitchBroadcastCache(IOFSwitch sw, OFPacketIn pi, FloodlightContext cntx) {
if (sw == null) return true;
// If the feature is disabled, always return false;
if (!broadcastCacheFeature) return false;
// Get the hash of the Ethernet packet.
Ethernet eth =
IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
long hash = pi.getInPort() * prime2 + eth.hashCode();
// some FORWARD_OR_FLOOD packets are unicast with unknown destination mac
return sw.updateBroadcastCache(hash, pi.getInPort());
}
@LogMessageDocs({
@LogMessageDoc(level="ERROR",
message="Failure writing deny flow mod",
explanation="An I/O error occurred while writing a " +
"deny flow mod to a switch",
recommendation=LogMessageDoc.CHECK_SWITCH),
})
public static boolean
blockHost(IFloodlightProviderService floodlightProvider,
SwitchPort sw_tup, long host_mac,
short hardTimeout, long cookie) {
if (sw_tup == null) {
return false;
}
IOFSwitch sw =
floodlightProvider.getSwitches().get(sw_tup.getSwitchDPID());
if (sw == null) return false;
int inputPort = sw_tup.getPort();
log.debug("blockHost sw={} port={} mac={}",
new Object[] { sw, sw_tup.getPort(), new Long(host_mac) });
// Create flow-mod based on packet-in and src-switch
OFFlowMod fm =
(OFFlowMod) floodlightProvider.getOFMessageFactory()
.getMessage(OFType.FLOW_MOD);
OFMatch match = new OFMatch();
List<OFAction> actions = new ArrayList<OFAction>(); // Set no action to
// drop
match.setDataLayerSource(Ethernet.toByteArray(host_mac))
.setInputPort((short)inputPort)
.setWildcards(OFMatch.OFPFW_ALL & ~OFMatch.OFPFW_DL_SRC
& ~OFMatch.OFPFW_IN_PORT);
fm.setCookie(cookie)
.setHardTimeout((short) hardTimeout)
.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
.setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
.setBufferId(OFPacketOut.BUFFER_ID_NONE)
.setMatch(match)
.setActions(actions)
.setLengthU(OFFlowMod.MINIMUM_LENGTH); // +OFActionOutput.MINIMUM_LENGTH);
try {
log.debug("write drop flow-mod sw={} match={} flow-mod={}",
new Object[] { sw, match, fm });
// TODO: can't use the message damper sine this method is static
sw.write(fm, null);
} catch (IOException e) {
log.error("Failure writing deny flow mod", e);
return false;
}
return true;
}
@Override
public void deviceAdded(IDevice device) {
// NOOP
}
@Override
public void deviceRemoved(IDevice device) {
// NOOP
}
@Override
public void deviceMoved(IDevice device) {
}
@Override
public void deviceIPV4AddrChanged(IDevice device) {
}
@Override
public void deviceVlanChanged(IDevice device) {
}
@Override
public boolean isCallbackOrderingPrereq(OFType type, String name) {
return (type.equals(OFType.PACKET_IN) &&
(name.equals("topology") ||
name.equals("devicemanager")));
}
@Override
public boolean isCallbackOrderingPostreq(OFType type, String name) {
return false;
}
}
| src/main/java/net/floodlightcontroller/routing/ForwardingBase.java | /**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.floodlightcontroller.routing;
import java.io.IOException;
import java.util.EnumSet;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.annotations.LogMessageCategory;
import net.floodlightcontroller.core.annotations.LogMessageDoc;
import net.floodlightcontroller.core.annotations.LogMessageDocs;
import net.floodlightcontroller.core.util.AppCookie;
import net.floodlightcontroller.counter.ICounterStoreService;
import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.devicemanager.IDeviceListener;
import net.floodlightcontroller.devicemanager.IDeviceService;
import net.floodlightcontroller.devicemanager.SwitchPort;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.IPacket;
import net.floodlightcontroller.routing.IRoutingService;
import net.floodlightcontroller.routing.IRoutingDecision;
import net.floodlightcontroller.routing.Route;
import net.floodlightcontroller.topology.ITopologyService;
import net.floodlightcontroller.topology.NodePortTuple;
import net.floodlightcontroller.util.OFMessageDamper;
import net.floodlightcontroller.util.TimedCache;
import org.openflow.protocol.OFFlowMod;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPacketIn;
import org.openflow.protocol.OFPacketOut;
import org.openflow.protocol.OFType;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract base class for implementing a forwarding module. Forwarding is
* responsible for programming flows to a switch in response to a policy
* decision.
*/
@LogMessageCategory("Flow Programming")
public abstract class ForwardingBase
implements IOFMessageListener, IDeviceListener {
protected static Logger log =
LoggerFactory.getLogger(ForwardingBase.class);
protected static int OFMESSAGE_DAMPER_CAPACITY = 50000; // TODO: find sweet spot
protected static int OFMESSAGE_DAMPER_TIMEOUT = 250; // ms
public static short FLOWMOD_DEFAULT_IDLE_TIMEOUT = 5; // in seconds
public static short FLOWMOD_DEFAULT_HARD_TIMEOUT = 0; // infinite
protected IFloodlightProviderService floodlightProvider;
protected IDeviceService deviceManager;
protected IRoutingService routingEngine;
protected ITopologyService topology;
protected ICounterStoreService counterStore;
protected OFMessageDamper messageDamper;
// for broadcast loop suppression
protected boolean broadcastCacheFeature = true;
public final int prime1 = 2633; // for hash calculation
public final static int prime2 = 4357; // for hash calculation
public TimedCache<Long> broadcastCache =
new TimedCache<Long>(100, 5*1000); // 5 seconds interval;
// flow-mod - for use in the cookie
public static final int FORWARDING_APP_ID = 2; // TODO: This must be managed
// by a global APP_ID class
public long appCookie = AppCookie.makeCookie(FORWARDING_APP_ID, 0);
// Comparator for sorting by SwitchCluster
public Comparator<SwitchPort> clusterIdComparator =
new Comparator<SwitchPort>() {
@Override
public int compare(SwitchPort d1, SwitchPort d2) {
Long d1ClusterId =
topology.getL2DomainId(d1.getSwitchDPID());
Long d2ClusterId =
topology.getL2DomainId(d2.getSwitchDPID());
return d1ClusterId.compareTo(d2ClusterId);
}
};
/**
* init data structures
*
*/
protected void init() {
messageDamper = new OFMessageDamper(OFMESSAGE_DAMPER_CAPACITY,
EnumSet.of(OFType.FLOW_MOD),
OFMESSAGE_DAMPER_TIMEOUT);
}
/**
* Adds a listener for devicemanager and registers for PacketIns.
*/
protected void startUp() {
deviceManager.addListener(this);
floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
}
/**
* Returns the application name "forwarding".
*/
@Override
public String getName() {
return "forwarding";
}
/**
* All subclasses must define this function if they want any specific
* forwarding action
*
* @param sw
* Switch that the packet came in from
* @param pi
* The packet that came in
* @param decision
* Any decision made by a policy engine
*/
public abstract Command
processPacketInMessage(IOFSwitch sw, OFPacketIn pi,
IRoutingDecision decision,
FloodlightContext cntx);
@Override
public Command receive(IOFSwitch sw, OFMessage msg,
FloodlightContext cntx) {
switch (msg.getType()) {
case PACKET_IN:
IRoutingDecision decision = null;
if (cntx != null)
decision =
IRoutingDecision.rtStore.get(cntx,
IRoutingDecision.CONTEXT_DECISION);
return this.processPacketInMessage(sw,
(OFPacketIn) msg,
decision,
cntx);
default:
break;
}
return Command.CONTINUE;
}
/**
* Push routes from back to front
* @param route Route to push
* @param match OpenFlow fields to match on
* @param srcSwPort Source switch port for the first hop
* @param dstSwPort Destination switch port for final hop
* @param cookie The cookie to set in each flow_mod
* @param cntx The floodlight context
* @param reqeustFlowRemovedNotifn if set to true then the switch would
* send a flow mod removal notification when the flow mod expires
* @param doFlush if set to true then the flow mod would be immediately
* written to the switch
* @param flowModCommand flow mod. command to use, e.g. OFFlowMod.OFPFC_ADD,
* OFFlowMod.OFPFC_MODIFY etc.
* @return srcSwitchIincluded True if the source switch is included in this route
*/
@LogMessageDocs({
@LogMessageDoc(level="WARN",
message="Unable to push route, switch at DPID {dpid} not available",
explanation="A switch along the calculated path for the " +
"flow has disconnected.",
recommendation=LogMessageDoc.CHECK_SWITCH),
@LogMessageDoc(level="ERROR",
message="Failure writing flow mod",
explanation="An I/O error occurred while writing a " +
"flow modification to a switch",
recommendation=LogMessageDoc.CHECK_SWITCH),
})
public boolean pushRoute(Route route, OFMatch match,
Integer wildcard_hints,
OFPacketIn pi,
long pinSwitch,
long cookie,
FloodlightContext cntx,
boolean reqeustFlowRemovedNotifn,
boolean doFlush,
short flowModCommand) {
boolean srcSwitchIncluded = false;
OFFlowMod fm =
(OFFlowMod) floodlightProvider.getOFMessageFactory()
.getMessage(OFType.FLOW_MOD);
OFActionOutput action = new OFActionOutput();
action.setMaxLength((short)0xffff);
List<OFAction> actions = new ArrayList<OFAction>();
actions.add(action);
fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
.setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
.setBufferId(OFPacketOut.BUFFER_ID_NONE)
.setCookie(cookie)
.setCommand(flowModCommand)
.setMatch(match)
.setActions(actions)
.setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH);
List<NodePortTuple> switchPortList = route.getPath();
for (int indx = switchPortList.size()-1; indx > 0; indx -= 2) {
// indx and indx-1 will always have the same switch DPID.
long switchDPID = switchPortList.get(indx).getNodeId();
IOFSwitch sw = floodlightProvider.getSwitches().get(switchDPID);
if (sw == null) {
if (log.isWarnEnabled()) {
log.warn("Unable to push route, switch at DPID {} " +
"not available", switchDPID);
}
return srcSwitchIncluded;
}
// set the match.
fm.setMatch(wildcard(match, sw, wildcard_hints));
// set buffer id if it is the source switch
if (1 == indx) {
// Set the flag to request flow-mod removal notifications only for the
// source switch. The removal message is used to maintain the flow
// cache. Don't set the flag for ARP messages - TODO generalize check
if ((reqeustFlowRemovedNotifn)
&& (match.getDataLayerType() != Ethernet.TYPE_ARP)) {
fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM);
match.setWildcards(fm.getMatch().getWildcards());
}
}
short outPort = switchPortList.get(indx).getPortId();
short inPort = switchPortList.get(indx-1).getPortId();
// set input and output ports on the switch
fm.getMatch().setInputPort(inPort);
((OFActionOutput)fm.getActions().get(0)).setPort(outPort);
try {
counterStore.updatePktOutFMCounterStore(sw, fm);
if (log.isTraceEnabled()) {
log.trace("Pushing Route flowmod routeIndx={} " +
"sw={} inPort={} outPort={}",
new Object[] {indx,
sw,
fm.getMatch().getInputPort(),
outPort });
}
messageDamper.write(sw, fm, cntx);
if (doFlush) {
sw.flush();
}
// Push the packet out the source switch
if (sw.getId() == pinSwitch) {
// TODO: Instead of doing a packetOut here we could also
// send a flowMod with bufferId set....
pushPacket(sw, match, pi, outPort, cntx);
srcSwitchIncluded = true;
}
} catch (IOException e) {
log.error("Failure writing flow mod", e);
}
try {
fm = fm.clone();
} catch (CloneNotSupportedException e) {
log.error("Failure cloning flow mod", e);
}
}
return srcSwitchIncluded;
}
protected OFMatch wildcard(OFMatch match, IOFSwitch sw,
Integer wildcard_hints) {
if (wildcard_hints != null) {
return match.clone().setWildcards(wildcard_hints.intValue());
}
return match.clone();
}
/**
* Pushes a packet-out to a switch. If bufferId != BUFFER_ID_NONE we
* assume that the packetOut switch is the same as the packetIn switch
* and we will use the bufferId
* Caller needs to make sure that inPort and outPort differs
* @param packet packet data to send
* @param sw switch from which packet-out is sent
* @param bufferId bufferId
* @param inPort input port
* @param outPort output port
* @param cntx context of the packet
* @param flush force to flush the packet.
*/
@LogMessageDocs({
@LogMessageDoc(level="ERROR",
message="BufferId is not and packet data is null. " +
"Cannot send packetOut. " +
"srcSwitch={dpid} inPort={port} outPort={port}",
explanation="The switch send a malformed packet-in." +
"The packet will be dropped",
recommendation=LogMessageDoc.REPORT_SWITCH_BUG),
@LogMessageDoc(level="ERROR",
message="Failure writing packet out",
explanation="An I/O error occurred while writing a " +
"packet out to a switch",
recommendation=LogMessageDoc.CHECK_SWITCH),
})
public void pushPacket(IPacket packet,
IOFSwitch sw,
int bufferId,
short inPort,
short outPort,
FloodlightContext cntx,
boolean flush) {
if (log.isTraceEnabled()) {
log.trace("PacketOut srcSwitch={} inPort={} outPort={}",
new Object[] {sw, inPort, outPort});
}
OFPacketOut po =
(OFPacketOut) floodlightProvider.getOFMessageFactory()
.getMessage(OFType.PACKET_OUT);
// set actions
List<OFAction> actions = new ArrayList<OFAction>();
actions.add(new OFActionOutput(outPort, (short) 0xffff));
po.setActions(actions)
.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
short poLength =
(short) (po.getActionsLength() + OFPacketOut.MINIMUM_LENGTH);
// set buffer_id, in_port
po.setBufferId(bufferId);
po.setInPort(inPort);
// set data - only if buffer_id == -1
if (po.getBufferId() == OFPacketOut.BUFFER_ID_NONE) {
if (packet == null) {
log.error("BufferId is not set and packet data is null. " +
"Cannot send packetOut. " +
"srcSwitch={} inPort={} outPort={}",
new Object[] {sw, inPort, outPort});
return;
}
byte[] packetData = packet.serialize();
poLength += packetData.length;
po.setPacketData(packetData);
}
po.setLength(poLength);
try {
counterStore.updatePktOutFMCounterStore(sw, po);
messageDamper.write(sw, po, cntx, flush);
} catch (IOException e) {
log.error("Failure writing packet out", e);
}
}
/**
* Pushes a packet-out to a switch. The assumption here is that
* the packet-in was also generated from the same switch. Thus, if the input
* port of the packet-in and the outport are the same, the function will not
* push the packet-out.
* @param sw switch that generated the packet-in, and from which packet-out is sent
* @param match OFmatch
* @param pi packet-in
* @param outport output port
* @param cntx context of the packet
*/
protected void pushPacket(IOFSwitch sw, OFMatch match, OFPacketIn pi,
short outport, FloodlightContext cntx) {
if (pi == null) {
return;
} else if (pi.getInPort() == outport){
log.warn("Packet out not sent as the outport matches inport. {}",
pi);
return;
}
// The assumption here is (sw) is the switch that generated the
// packet-in. If the input port is the same as output port, then
// the packet-out should be ignored.
if (pi.getInPort() == outport) {
if (log.isDebugEnabled()) {
log.debug("Attempting to do packet-out to the same " +
"interface as packet-in. Dropping packet. " +
" SrcSwitch={}, match = {}, pi={}",
new Object[]{sw, match, pi});
return;
}
}
if (log.isTraceEnabled()) {
log.trace("PacketOut srcSwitch={} match={} pi={}",
new Object[] {sw, match, pi});
}
OFPacketOut po =
(OFPacketOut) floodlightProvider.getOFMessageFactory()
.getMessage(OFType.PACKET_OUT);
// set actions
List<OFAction> actions = new ArrayList<OFAction>();
actions.add(new OFActionOutput(outport, (short) 0xffff));
po.setActions(actions)
.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
short poLength =
(short) (po.getActionsLength() + OFPacketOut.MINIMUM_LENGTH);
// If the switch doens't support buffering set the buffer id to be none
// otherwise it'll be the the buffer id of the PacketIn
if (sw.getBuffers() == 0) {
// We set the PI buffer id here so we don't have to check again below
pi.setBufferId(OFPacketOut.BUFFER_ID_NONE);
po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
} else {
po.setBufferId(pi.getBufferId());
}
po.setInPort(pi.getInPort());
// If the buffer id is none or the switch doesn's support buffering
// we send the data with the packet out
if (pi.getBufferId() == OFPacketOut.BUFFER_ID_NONE) {
byte[] packetData = pi.getPacketData();
poLength += packetData.length;
po.setPacketData(packetData);
}
po.setLength(poLength);
try {
counterStore.updatePktOutFMCounterStore(sw, po);
messageDamper.write(sw, po, cntx);
} catch (IOException e) {
log.error("Failure writing packet out", e);
}
}
/**
* Write packetout message to sw with output actions to one or more
* output ports with inPort/outPorts passed in.
* @param packetData
* @param sw
* @param inPort
* @param ports
* @param cntx
*/
public void packetOutMultiPort(byte[] packetData,
IOFSwitch sw,
short inPort,
Set<Integer> outPorts,
FloodlightContext cntx) {
//setting actions
List<OFAction> actions = new ArrayList<OFAction>();
Iterator<Integer> j = outPorts.iterator();
while (j.hasNext())
{
actions.add(new OFActionOutput(j.next().shortValue(),
(short) 0));
}
OFPacketOut po =
(OFPacketOut) floodlightProvider.getOFMessageFactory().
getMessage(OFType.PACKET_OUT);
po.setActions(actions);
po.setActionsLength((short) (OFActionOutput.MINIMUM_LENGTH *
outPorts.size()));
// set buffer-id to BUFFER_ID_NONE, and set in-port to OFPP_NONE
po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
po.setInPort(inPort);
// data (note buffer_id is always BUFFER_ID_NONE) and length
short poLength = (short)(po.getActionsLength() +
OFPacketOut.MINIMUM_LENGTH);
poLength += packetData.length;
po.setPacketData(packetData);
po.setLength(poLength);
try {
counterStore.updatePktOutFMCounterStore(sw, po);
if (log.isTraceEnabled()) {
log.trace("write broadcast packet on switch-id={} " +
"interfaces={} packet-out={}",
new Object[] {sw.getId(), outPorts, po});
}
messageDamper.write(sw, po, cntx);
} catch (IOException e) {
log.error("Failure writing packet out", e);
}
}
/**
* @see packetOutMultiPort
* Accepts a PacketIn instead of raw packet data. Note that the inPort
* and switch can be different than the packet in switch/port
*/
public void packetOutMultiPort(OFPacketIn pi,
IOFSwitch sw,
short inPort,
Set<Integer> outPorts,
FloodlightContext cntx) {
packetOutMultiPort(pi.getPacketData(), sw, inPort, outPorts, cntx);
}
/**
* @see packetOutMultiPort
* Accepts an IPacket instead of raw packet data. Note that the inPort
* and switch can be different than the packet in switch/port
*/
public void packetOutMultiPort(IPacket packet,
IOFSwitch sw,
short inPort,
Set<Integer> outPorts,
FloodlightContext cntx) {
packetOutMultiPort(packet.serialize(), sw, inPort, outPorts, cntx);
}
protected boolean isInBroadcastCache(IOFSwitch sw, OFPacketIn pi,
FloodlightContext cntx) {
// Get the cluster id of the switch.
// Get the hash of the Ethernet packet.
if (sw == null) return true;
// If the feature is disabled, always return false;
if (!broadcastCacheFeature) return false;
Ethernet eth =
IFloodlightProviderService.bcStore.get(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
Long broadcastHash;
broadcastHash = topology.getL2DomainId(sw.getId()) * prime1 +
pi.getInPort() * prime2 + eth.hashCode();
if (broadcastCache.update(broadcastHash)) {
sw.updateBroadcastCache(broadcastHash, pi.getInPort());
return true;
} else {
return false;
}
}
protected boolean isInSwitchBroadcastCache(IOFSwitch sw, OFPacketIn pi, FloodlightContext cntx) {
if (sw == null) return true;
// If the feature is disabled, always return false;
if (!broadcastCacheFeature) return false;
// Get the hash of the Ethernet packet.
Ethernet eth =
IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
long hash = pi.getInPort() * prime2 + eth.hashCode();
// some FORWARD_OR_FLOOD packets are unicast with unknown destination mac
return sw.updateBroadcastCache(hash, pi.getInPort());
}
@LogMessageDocs({
@LogMessageDoc(level="ERROR",
message="Failure writing deny flow mod",
explanation="An I/O error occurred while writing a " +
"deny flow mod to a switch",
recommendation=LogMessageDoc.CHECK_SWITCH),
})
public static boolean
blockHost(IFloodlightProviderService floodlightProvider,
SwitchPort sw_tup, long host_mac,
short hardTimeout, long cookie) {
if (sw_tup == null) {
return false;
}
IOFSwitch sw =
floodlightProvider.getSwitches().get(sw_tup.getSwitchDPID());
if (sw == null) return false;
int inputPort = sw_tup.getPort();
log.debug("blockHost sw={} port={} mac={}",
new Object[] { sw, sw_tup.getPort(), new Long(host_mac) });
// Create flow-mod based on packet-in and src-switch
OFFlowMod fm =
(OFFlowMod) floodlightProvider.getOFMessageFactory()
.getMessage(OFType.FLOW_MOD);
OFMatch match = new OFMatch();
List<OFAction> actions = new ArrayList<OFAction>(); // Set no action to
// drop
match.setDataLayerSource(Ethernet.toByteArray(host_mac))
.setInputPort((short)inputPort)
.setWildcards(OFMatch.OFPFW_ALL & ~OFMatch.OFPFW_DL_SRC
& ~OFMatch.OFPFW_IN_PORT);
fm.setCookie(cookie)
.setHardTimeout((short) hardTimeout)
.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT)
.setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT)
.setBufferId(OFPacketOut.BUFFER_ID_NONE)
.setMatch(match)
.setActions(actions)
.setLengthU(OFFlowMod.MINIMUM_LENGTH); // +OFActionOutput.MINIMUM_LENGTH);
try {
log.debug("write drop flow-mod sw={} match={} flow-mod={}",
new Object[] { sw, match, fm });
// TODO: can't use the message damper sine this method is static
sw.write(fm, null);
} catch (IOException e) {
log.error("Failure writing deny flow mod", e);
return false;
}
return true;
}
@Override
public void deviceAdded(IDevice device) {
// NOOP
}
@Override
public void deviceRemoved(IDevice device) {
// NOOP
}
@Override
public void deviceMoved(IDevice device) {
}
@Override
public void deviceIPV4AddrChanged(IDevice device) {
}
@Override
public void deviceVlanChanged(IDevice device) {
}
@Override
public boolean isCallbackOrderingPrereq(OFType type, String name) {
return (type.equals(OFType.PACKET_IN) &&
(name.equals("topology") ||
name.equals("devicemanager")));
}
@Override
public boolean isCallbackOrderingPostreq(OFType type, String name) {
return false;
}
}
| Reduce default size of OFMessageDamper cache to be nicer to the jvm
| src/main/java/net/floodlightcontroller/routing/ForwardingBase.java | Reduce default size of OFMessageDamper cache to be nicer to the jvm |
|
Java | apache-2.0 | 80891c58e641b1ea79a481b5ead869c52b3ffd4e | 0 | enternoescape/opendct,enternoescape/opendct,enternoescape/opendct | /*
* Copyright 2015 The OpenDCT Authors. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package opendct;
import opendct.channel.ChannelManager;
import opendct.config.CommandLine;
import opendct.config.Config;
import opendct.config.ExitCode;
import opendct.power.NetworkPowerEventManger;
import opendct.power.PowerMessageManager;
import opendct.sagetv.SageTVManager;
import opendct.tuning.discovery.DiscoveryManager;
import opendct.tuning.discovery.discoverers.HDHomeRunDiscoverer;
import opendct.tuning.upnp.UpnpManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import java.io.File;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) throws Exception {
logger.info("Starting OpenDCT {}...", Config.VERSION);
Runtime.getRuntime().addShutdownHook(new Thread("Shutdown") {
@Override
public void run() {
shutdown();
}
});
if (!CommandLine.parseCommandLineOptions(args)) {
// The method will automatically print out the valid parameters if there is a
// problem and then return false.
logger.exit();
ExitCode.PARAMETER_ISSUE.terminateJVM();
return;
}
if (!Config.setConfigDirectory(CommandLine.getConfigDir())) {
logger.exit();
ExitCode.CONFIG_DIRECTORY.terminateJVM();
return;
}
File restartFile = new File(Config.getConfigDirectory() + Config.DIR_SEPARATOR + "restart");
if (restartFile.exists()) {
if (!restartFile.delete()) {
logger.error("Unable to delete the file '{}'.", restartFile.getName());
}
}
if (!Config.loadConfig()) {
logger.exit();
ExitCode.CONFIG_ISSUE.terminateJVM();
return;
}
//==========================================================================================
// This is all of the log4j2 runtime configuration.
//==========================================================================================
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
final LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
ctx.reconfigure();
// Turn off console logging. With this turned off, all you will might see is that the
// program started.
if (CommandLine.isLogToConsole()) {
if (config.getConfigurationSource().getFile() != null) {
try {
System.out.close();
logger.info("Console logging is disabled.");
} catch (Exception e) {
logger.error("There was an unexpected exception while trying to turn off console logging => ", e);
}
} else {
logger.info("Unable to turn off console due to missing configuration.");
}
}
logger.info("OpenDCT logging to the directory '{}'.", CommandLine.getLogDir());
// This takes care of everything to do with logging from cling. The default configuration
// only reports severe errors.
UpnpManager.configureUPnPLogging();
// I think this should be turned on by default for now so it actually gets tested.
boolean enablePowerManagement = Config.getBoolean("pm.enabled", true);
if (enablePowerManagement) {
if (!PowerMessageManager.EVENTS.startPump()) {
// Save the configuration data as it is so the pm.enabled property will already be
// in the file.
Config.saveConfig();
System.exit(ExitCode.PM_INIT.CODE);
ExitCode.PM_INIT.terminateJVM(
"If you do not want to use power state features, set pm.enabled=false in '" +
Config.getDefaultConfigFilename() + "'");
return;
}
Runtime.getRuntime().addShutdownHook(new Thread("PowerMessageManagerShutdown") {
@Override
public void run() {
logger.info("Stopping power messages...");
PowerMessageManager.EVENTS.stopPump();
}
});
}
// This will enable us to wait for the network to become available first after a standby
// event.
PowerMessageManager.EVENTS.addListener(NetworkPowerEventManger.POWER_EVENT_LISTENER);
// This will place the SageTVManager second in the queue for standby events. It will prevent
// any further communication from SageTV that might activate the capture devices when we are
// trying to stop them.
PowerMessageManager.EVENTS.addListener(SageTVManager.POWER_EVENT_LISTENER);
Runtime.getRuntime().addShutdownHook(new Thread("SageTVManagerShutdown") {
@Override
public void run() {
logger.info("Stopping all SageTV socket servers...");
SageTVManager.stopAllSocketServers();
SageTVManager.stopAndClearAllCaptureDevices();
}
});
// This loads all of the currently saved channel lineups from the lineups folder.
ChannelManager.loadChannelLineups();
Runtime.getRuntime().addShutdownHook(new Thread("ChannelManagerShutdown") {
@Override
public void run() {
logger.info("Stopping all channel update threads...");
ChannelManager.stopAllOfflineScansAndWait();
ChannelManager.saveChannelLineups();
}
});
// This starts the timer for all of the capture devices to be loaded. The default timeout is
// 30 seconds. The default device count is 0. These values are saved after the first run and
// can be changed after stopping the program.
SageTVManager.startWaitingForCaptureDevices();
// When this is set to true SageTV will open all ports assigned to any capture device in the
// configuration properties.
boolean earlyPortAssignment = Config.getBoolean("sagetv.early_port_assignment", false);
// When this is set to true, all new devices will receive the same communication port
// number. This is intelligently handled when SageTVManager creates instances of
// SageTVSocketServer. When a new instance is being added, if it shares the same port
// number as an instance that has already started, it will just be added to that
// instances pool of capture devices.
boolean incrementPortForNewDevices = Config.getBoolean("sagetv.new.device.increment_port", false);
int sageTVdefaultEncoderMerit = Config.getInteger("sagetv.new.device.default_encoder_merit", 0);
int sageTVdefaultTuningDelay = Config.getInteger("sagetv.new.device.default_tuning_delay", 0);
int sageTVdefaultDiscoveryPort = Config.getInteger("sagetv.encoder_discovery_port", 8271);
// Currently the program doesn't do much without this part, but in the future we might have
// a capture device that doesn't use UPnP so we would want it disabled if we don't need it.
boolean useUPnP = Config.getBoolean("upnp.enabled", true);
// If this is enabled the program will
boolean useDiscoveryManager = Config.getBoolean("discovery.exp_enabled", false);
Config.saveConfig();
if (earlyPortAssignment) {
SageTVManager.addAndStartSocketServers(Config.getAllSocketServerPorts());
}
if (useUPnP) {
UpnpManager.startUpnpServices();
PowerMessageManager.EVENTS.addListener(UpnpManager.POWER_EVENT_LISTENER);
Runtime.getRuntime().addShutdownHook(new Thread("UpnpManagerShutdown") {
@Override
public void run() {
logger.info("Stopping UPnP services...");
UpnpManager.stopUpnpServices();
}
});
}
if (useDiscoveryManager) {
DiscoveryManager.startDeviceDiscovery();
DiscoveryManager.addDiscoverer(new HDHomeRunDiscoverer());
PowerMessageManager.EVENTS.addListener(DiscoveryManager.POWER_EVENT_LISTENER);
Runtime.getRuntime().addShutdownHook(new Thread("DiscoveryManagerShutdown") {
@Override
public void run() {
logger.info("Stopping device discovery services...");
try {
DiscoveryManager.stopDeviceDiscovery();
} catch (InterruptedException e) {
logger.debug("Stopping device discovery services was interrupted => ", e);
}
}
});
}
// Don't proceed until we have every required device loaded.
SageTVManager.blockUntilCaptureDevicesLoaded();
boolean channelUpdates = Config.getBoolean("channels.update", true);
if (channelUpdates) {
ChannelManager.startUpdateChannelsThread();
PowerMessageManager.EVENTS.addListener(ChannelManager.POWER_EVENT_LISTENER);
}
Config.saveConfig();
if (CommandLine.isConfigOnly()) {
logger.info("Running in config only mode for '{}' seconds...", CommandLine.getRunSeconds());
Thread.sleep(CommandLine.getRunSeconds() * 1000);
Config.logCleanup();
} else if (CommandLine.isDaemon()) {
logger.info("Running in daemon mode...");
// Maybe we can do more with this thread than just wait for the program to terminate.
while (!Config.isShutdown()) {
Thread.sleep(60000);
Config.logCleanup();
}
} else {
if (CommandLine.isSuspendTest()) {
logger.info("Press ENTER at any time to suspend...");
System.in.read();
PowerMessageManager.EVENTS.testSuspend();
logger.info("Press ENTER at any time to resume...");
System.in.read();
PowerMessageManager.EVENTS.testResume();
}
logger.info("Press ENTER at any time to exit...");
System.in.read();
Config.logCleanup();
}
System.exit(0);
}
public static void shutdown() {
logger.info("OpenDCT has received a signal to stop.");
logger.info("Saving current configuration...");
Config.saveConfig();
// This will allow the main thread to stop.
Config.setShutdown();
logger.exit();
}
}
| src/main/java/opendct/Main.java | /*
* Copyright 2015 The OpenDCT Authors. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package opendct;
import opendct.channel.ChannelManager;
import opendct.config.CommandLine;
import opendct.config.Config;
import opendct.config.ExitCode;
import opendct.power.NetworkPowerEventManger;
import opendct.power.PowerMessageManager;
import opendct.sagetv.SageTVManager;
import opendct.tuning.discovery.DiscoveryManager;
import opendct.tuning.upnp.UpnpManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import java.io.File;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) throws Exception {
logger.info("Starting OpenDCT {}...", Config.VERSION);
Runtime.getRuntime().addShutdownHook(new Thread("Shutdown") {
@Override
public void run() {
shutdown();
}
});
if (!CommandLine.parseCommandLineOptions(args)) {
// The method will automatically print out the valid parameters if there is a
// problem and then return false.
logger.exit();
ExitCode.PARAMETER_ISSUE.terminateJVM();
return;
}
if (!Config.setConfigDirectory(CommandLine.getConfigDir())) {
logger.exit();
ExitCode.CONFIG_DIRECTORY.terminateJVM();
return;
}
File restartFile = new File(Config.getConfigDirectory() + Config.DIR_SEPARATOR + "restart");
if (restartFile.exists()) {
if (!restartFile.delete()) {
logger.error("Unable to delete the file '{}'.", restartFile.getName());
}
}
if (!Config.loadConfig()) {
logger.exit();
ExitCode.CONFIG_ISSUE.terminateJVM();
return;
}
//==========================================================================================
// This is all of the log4j2 runtime configuration.
//==========================================================================================
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
final LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
ctx.reconfigure();
// Turn off console logging. With this turned off, all you will might see is that the
// program started.
if (CommandLine.isLogToConsole()) {
if (config.getConfigurationSource().getFile() != null) {
try {
System.out.close();
logger.info("Console logging is disabled.");
} catch (Exception e) {
logger.error("There was an unexpected exception while trying to turn off console logging => ", e);
}
} else {
logger.info("Unable to turn off console due to missing configuration.");
}
}
logger.info("OpenDCT logging to the directory '{}'.", CommandLine.getLogDir());
// This takes care of everything to do with logging from cling. The default configuration
// only reports severe errors.
UpnpManager.configureUPnPLogging();
// I think this should be turned on by default for now so it actually gets tested.
boolean enablePowerManagement = Config.getBoolean("pm.enabled", true);
if (enablePowerManagement) {
if (!PowerMessageManager.EVENTS.startPump()) {
// Save the configuration data as it is so the pm.enabled property will already be
// in the file.
Config.saveConfig();
System.exit(ExitCode.PM_INIT.CODE);
ExitCode.PM_INIT.terminateJVM(
"If you do not want to use power state features, set pm.enabled=false in '" +
Config.getDefaultConfigFilename() + "'");
return;
}
Runtime.getRuntime().addShutdownHook(new Thread("PowerMessageManagerShutdown") {
@Override
public void run() {
logger.info("Stopping power messages...");
PowerMessageManager.EVENTS.stopPump();
}
});
}
// This will enable us to wait for the network to become available first after a standby
// event.
PowerMessageManager.EVENTS.addListener(NetworkPowerEventManger.POWER_EVENT_LISTENER);
// This will place the SageTVManager second in the queue for standby events. It will prevent
// any further communication from SageTV that might activate the capture devices when we are
// trying to stop them.
PowerMessageManager.EVENTS.addListener(SageTVManager.POWER_EVENT_LISTENER);
Runtime.getRuntime().addShutdownHook(new Thread("SageTVManagerShutdown") {
@Override
public void run() {
logger.info("Stopping all SageTV socket servers...");
SageTVManager.stopAllSocketServers();
SageTVManager.stopAndClearAllCaptureDevices();
}
});
// This loads all of the currently saved channel lineups from the lineups folder.
ChannelManager.loadChannelLineups();
Runtime.getRuntime().addShutdownHook(new Thread("ChannelManagerShutdown") {
@Override
public void run() {
logger.info("Stopping all channel update threads...");
ChannelManager.stopAllOfflineScansAndWait();
ChannelManager.saveChannelLineups();
}
});
// This starts the timer for all of the capture devices to be loaded. The default timeout is
// 30 seconds. The default device count is 0. These values are saved after the first run and
// can be changed after stopping the program.
SageTVManager.startWaitingForCaptureDevices();
// When this is set to true SageTV will open all ports assigned to any capture device in the
// configuration properties.
boolean earlyPortAssignment = Config.getBoolean("sagetv.early_port_assignment", false);
// When this is set to true, all new devices will receive the same communication port
// number. This is intelligently handled when SageTVManager creates instances of
// SageTVSocketServer. When a new instance is being added, if it shares the same port
// number as an instance that has already started, it will just be added to that
// instances pool of capture devices.
boolean incrementPortForNewDevices = Config.getBoolean("sagetv.new.device.increment_port", false);
int sageTVdefaultEncoderMerit = Config.getInteger("sagetv.new.device.default_encoder_merit", 0);
int sageTVdefaultTuningDelay = Config.getInteger("sagetv.new.device.default_tuning_delay", 0);
int sageTVdefaultDiscoveryPort = Config.getInteger("sagetv.encoder_discovery_port", 8271);
// Currently the program doesn't do much without this part, but in the future we might have
// a capture device that doesn't use UPnP so we would want it disabled if we don't need it.
boolean useUPnP = Config.getBoolean("upnp.enabled", true);
// If this is enabled the program will
boolean useDiscoveryManager = Config.getBoolean("discovery.exp_enabled", false);
Config.saveConfig();
if (earlyPortAssignment) {
SageTVManager.addAndStartSocketServers(Config.getAllSocketServerPorts());
}
if (useUPnP) {
UpnpManager.startUpnpServices();
PowerMessageManager.EVENTS.addListener(UpnpManager.POWER_EVENT_LISTENER);
Runtime.getRuntime().addShutdownHook(new Thread("UpnpManagerShutdown") {
@Override
public void run() {
logger.info("Stopping UPnP services...");
UpnpManager.stopUpnpServices();
}
});
}
if (useDiscoveryManager) {
DiscoveryManager.startDeviceDiscovery();
PowerMessageManager.EVENTS.addListener(DiscoveryManager.POWER_EVENT_LISTENER);
Runtime.getRuntime().addShutdownHook(new Thread("DiscoveryManagerShutdown") {
@Override
public void run() {
logger.info("Stopping device discovery services...");
try {
DiscoveryManager.stopDeviceDiscovery();
} catch (InterruptedException e) {
logger.debug("Stopping device discovery services was interrupted => ", e);
}
}
});
}
// Don't proceed until we have every required device loaded.
SageTVManager.blockUntilCaptureDevicesLoaded();
boolean channelUpdates = Config.getBoolean("channels.update", true);
if (channelUpdates) {
ChannelManager.startUpdateChannelsThread();
PowerMessageManager.EVENTS.addListener(ChannelManager.POWER_EVENT_LISTENER);
}
Config.saveConfig();
if (CommandLine.isConfigOnly()) {
logger.info("Running in config only mode for '{}' seconds...", CommandLine.getRunSeconds());
Thread.sleep(CommandLine.getRunSeconds() * 1000);
Config.logCleanup();
} else if (CommandLine.isDaemon()) {
logger.info("Running in daemon mode...");
// Maybe we can do more with this thread than just wait for the program to terminate.
while (!Config.isShutdown()) {
Thread.sleep(60000);
Config.logCleanup();
}
} else {
if (CommandLine.isSuspendTest()) {
logger.info("Press ENTER at any time to suspend...");
System.in.read();
PowerMessageManager.EVENTS.testSuspend();
logger.info("Press ENTER at any time to resume...");
System.in.read();
PowerMessageManager.EVENTS.testResume();
}
logger.info("Press ENTER at any time to exit...");
System.in.read();
Config.logCleanup();
}
System.exit(0);
}
public static void shutdown() {
logger.info("OpenDCT has received a signal to stop.");
logger.info("Saving current configuration...");
Config.saveConfig();
// This will allow the main thread to stop.
Config.setShutdown();
logger.exit();
}
}
| Explicitly loading HDHomeRunDiscoverer until the automated reflection code is in place.
| src/main/java/opendct/Main.java | Explicitly loading HDHomeRunDiscoverer until the automated reflection code is in place. |
|
Java | apache-2.0 | da9612e185cc3d5b98fa22072cbbfc101fcfb935 | 0 | lastaflute/lastaflute-test-fortress,lastaflute/lastaflute-test-fortress,lastaflute/lastaflute-test-fortress,lastaflute/lastaflute-test-fortress,lastaflute/lastaflute-test-fortress,lastaflute/lastaflute-test-fortress,lastaflute/lastaflute-test-fortress | /*
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.docksidestage.app.web.wx.lastadoc;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.lastaflute.web.validation.Required;
/**
* @author jflute
*/
public class WxLastadocForm extends WxLastadocExtendsForm {
@Length(max = 94)
@Pattern(regexp = "mystic><@\"'bigband")
public String sea;
@Valid
public AmbaPart amba;
public static class AmbaPart {
// #hope jflute overridden by miraco#amba for now (2019/01/17)
/** official full name of amba */
@Required
public String fullName;
/** room count of amba */
@Required
public Integer roomCount;
}
@Valid
public MiracoPart miraco;
public static class MiracoPart {
/** official full name of miraco */
@Required
public String fullName;
/** room count of habor side */
@Required
public Integer harborRoomCount;
/** room count of venezia side */
@Required
public Integer veneziaRoomCount;
@Valid
public AmbaPart amba;
public static class AmbaPart {
/** official full name of miraco#amba */
@Required
public String fullName;
/** room count of amba */
@Required
public Integer roomCount;
}
}
@Valid
public DohotelPart dohotel;
public static class DohotelPart {
/** official full name of dohotel */
@Required
public String fullName;
/** room count of dohotel */
@Required
public Integer roomCount;
}
}
| src/main/java/org/docksidestage/app/web/wx/lastadoc/WxLastadocForm.java | /*
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.docksidestage.app.web.wx.lastadoc;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.lastaflute.web.validation.Required;
/**
* @author jflute
*/
public class WxLastadocForm extends WxLastadocExtendsForm {
@Length(max = 94)
@Pattern(regexp = "mystic><@\"'bigband")
public String sea;
@Valid
public AmbaPart amba;
public static class AmbaPart {
/** official full name of amba */
@Required
public String fullName;
/** room count of amba */
@Required
public Integer roomCount;
}
@Valid
public MiracoPart miraco;
public static class MiracoPart {
/** official full name of miraco */
@Required
public String fullName;
/** room count of habor side */
@Required
public Integer harborRoomCount;
/** room count of venezia side */
@Required
public Integer veneziaRoomCount;
@Valid
public AmbaPart amba;
public static class AmbaPart {
/** official full name of miraco#amba */
@Required
public String fullName;
/** room count of amba */
@Required
public Integer roomCount;
}
}
@Valid
public DohotelPart dohotel;
public static class DohotelPart {
/** official full name of dohotel */
@Required
public String fullName;
/** room count of dohotel */
@Required
public Integer roomCount;
}
}
| #hope jflute overridden by miraco#amba for now | src/main/java/org/docksidestage/app/web/wx/lastadoc/WxLastadocForm.java | #hope jflute overridden by miraco#amba for now |
|
Java | apache-2.0 | cf74cfa6dee9afa56e056c8e012a7bc3651712b9 | 0 | leapframework/framework,leapframework/framework,leapframework/framework,leapframework/framework | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leap.oauth2.server.openid;
import java.util.LinkedHashMap;
import java.util.Map;
import leap.core.annotation.Inject;
import leap.core.security.token.jwt.JWT;
import leap.core.security.token.jwt.JwtSigner;
import leap.core.security.token.jwt.MacSigner;
import leap.lang.New;
import leap.lang.Strings;
import leap.oauth2.server.OAuth2Params;
import leap.oauth2.server.authc.AuthzAuthentication;
import leap.oauth2.server.OAuth2AuthzServerConfig;
import leap.oauth2.server.client.AuthzClient;
import leap.web.security.user.UserDetails;
public class JwtIdTokenGenerator implements IdTokenGenerator {
protected @Inject OAuth2AuthzServerConfig config;
@Override
public String generateIdToken(AuthzAuthentication authc) {
return generateIdToken(authc,New.hashMap());
}
@Override
public String generateIdToken(AuthzAuthentication authc, Map<String, Object> extend) {
return generateIdToken(authc, extend, config.getDefaultIdTokenExpires());
}
@Override
public String generateIdToken(AuthzAuthentication authc, Map<String, Object> extend, int expiresIn) {
JwtSigner signer = getJwtSigner(authc, expiresIn);
Map<String, Object> claims = getJwtClaims(authc, extend, expiresIn);
return signer.sign(claims);
}
protected JwtSigner getJwtSigner(AuthzAuthentication authc, int expires) {
AuthzClient client = authc.getClientDetails();
return new MacSigner(client.getSecret(), expires);
}
protected Map<String, Object> getJwtClaims(AuthzAuthentication authc, Map<String, Object> extend, int expiresIn) {
OAuth2Params params = authc.getParams();
AuthzClient client = authc.getClientDetails();
UserDetails user = authc.getUserDetails();
Map<String, Object> claims = new LinkedHashMap<String, Object>();
/* Example claims in Open ID Connnect.
{
"iss": "http://server.example.com",
"sub": "248289761001",
"aud": "s6BhdRkqt3",
"nonce": "n-0S6_WzA2Mj",
"exp": 1311281970,
"iat": 1311280970,
"name": "Jane Doe",
"given_name": "Jane",
"family_name": "Doe",
"gender": "female",
"birthdate": "0000-10-31",
"email": "[email protected]",
"picture": "http://example.com/janedoe/me.jpg"
}
*/
claims.put(JWT.CLAIM_AUDIENCE, client.getId());
claims.put(JWT.CLAIM_SUBJECT, user.getId().toString());
claims.put(JWT.CLAIM_EXPIRATION_TIME, System.currentTimeMillis()/1000L+expiresIn);
claims.put("name", user.getName());
claims.put("username", user.getLoginName());
//TODO : other user properties
String nonce = params.getNonce();
if(!Strings.isEmpty(nonce)) {
claims.put(OAuth2Params.NONCE, nonce);
}
if(extend != null){
extend.forEach((s, o) -> claims.put(s,o));
}
return claims;
}
} | oauth2/server/src/main/java/leap/oauth2/server/openid/JwtIdTokenGenerator.java | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leap.oauth2.server.openid;
import java.util.LinkedHashMap;
import java.util.Map;
import leap.core.annotation.Inject;
import leap.core.security.token.jwt.JWT;
import leap.core.security.token.jwt.JwtSigner;
import leap.core.security.token.jwt.MacSigner;
import leap.lang.New;
import leap.lang.Strings;
import leap.oauth2.server.OAuth2Params;
import leap.oauth2.server.authc.AuthzAuthentication;
import leap.oauth2.server.OAuth2AuthzServerConfig;
import leap.oauth2.server.client.AuthzClient;
import leap.web.security.user.UserDetails;
public class JwtIdTokenGenerator implements IdTokenGenerator {
protected @Inject OAuth2AuthzServerConfig config;
@Override
public String generateIdToken(AuthzAuthentication authc) {
return generateIdToken(authc,New.hashMap());
}
@Override
public String generateIdToken(AuthzAuthentication authc, Map<String, Object> extend) {
return generateIdToken(authc, extend, config.getDefaultIdTokenExpires());
}
@Override
public String generateIdToken(AuthzAuthentication authc, Map<String, Object> extend, int expiresIn) {
JwtSigner signer = getJwtSigner(authc, expiresIn);
Map<String, Object> claims = getJwtClaims(authc, extend, expiresIn);
return signer.sign(claims);
}
protected JwtSigner getJwtSigner(AuthzAuthentication authc, int expires) {
AuthzClient client = authc.getClientDetails();
return new MacSigner(client.getSecret(), expires);
}
protected Map<String, Object> getJwtClaims(AuthzAuthentication authc, Map<String, Object> extend, int expiresIn) {
OAuth2Params params = authc.getParams();
AuthzClient client = authc.getClientDetails();
UserDetails user = authc.getUserDetails();
Map<String, Object> claims = new LinkedHashMap<String, Object>();
/* Example claims in Open ID Connnect.
{
"iss": "http://server.example.com",
"sub": "248289761001",
"aud": "s6BhdRkqt3",
"nonce": "n-0S6_WzA2Mj",
"exp": 1311281970,
"iat": 1311280970,
"name": "Jane Doe",
"given_name": "Jane",
"family_name": "Doe",
"gender": "female",
"birthdate": "0000-10-31",
"email": "[email protected]",
"picture": "http://example.com/janedoe/me.jpg"
}
*/
claims.put(JWT.CLAIM_AUDIENCE, client.getId());
claims.put(JWT.CLAIM_SUBJECT, user.getId().toString());
claims.put(JWT.CLAIM_EXPIRATION_TIME, System.currentTimeMillis()/1000L+expiresIn);
claims.put("name", user.getName());
claims.put("login_name", user.getLoginName());
//TODO : other user properties
String nonce = params.getNonce();
if(!Strings.isEmpty(nonce)) {
claims.put(OAuth2Params.NONCE, nonce);
}
if(extend != null){
extend.forEach((s, o) -> claims.put(s,o));
}
return claims;
}
} | change login_name to username
| oauth2/server/src/main/java/leap/oauth2/server/openid/JwtIdTokenGenerator.java | change login_name to username |
|
Java | apache-2.0 | e77cec85d472cb147b01e32a844f823063823942 | 0 | ChangerYoung/alluxio,ChangerYoung/alluxio,maobaolong/alluxio,wwjiang007/alluxio,Reidddddd/mo-alluxio,yuluo-ding/alluxio,aaudiber/alluxio,bf8086/alluxio,apc999/alluxio,ShailShah/alluxio,bf8086/alluxio,ShailShah/alluxio,Reidddddd/alluxio,madanadit/alluxio,riversand963/alluxio,maobaolong/alluxio,wwjiang007/alluxio,Alluxio/alluxio,PasaLab/tachyon,maobaolong/alluxio,wwjiang007/alluxio,jsimsa/alluxio,aaudiber/alluxio,WilliamZapata/alluxio,WilliamZapata/alluxio,ChangerYoung/alluxio,calvinjia/tachyon,jswudi/alluxio,PasaLab/tachyon,Alluxio/alluxio,wwjiang007/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,aaudiber/alluxio,Alluxio/alluxio,WilliamZapata/alluxio,madanadit/alluxio,maobaolong/alluxio,calvinjia/tachyon,PasaLab/tachyon,Reidddddd/mo-alluxio,ShailShah/alluxio,PasaLab/tachyon,Reidddddd/alluxio,wwjiang007/alluxio,maobaolong/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,uronce-cc/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,jswudi/alluxio,calvinjia/tachyon,apc999/alluxio,WilliamZapata/alluxio,calvinjia/tachyon,apc999/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,calvinjia/tachyon,Reidddddd/alluxio,wwjiang007/alluxio,yuluo-ding/alluxio,calvinjia/tachyon,yuluo-ding/alluxio,maobaolong/alluxio,wwjiang007/alluxio,madanadit/alluxio,Alluxio/alluxio,bf8086/alluxio,bf8086/alluxio,maboelhassan/alluxio,WilliamZapata/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,Alluxio/alluxio,riversand963/alluxio,calvinjia/tachyon,yuluo-ding/alluxio,PasaLab/tachyon,madanadit/alluxio,madanadit/alluxio,wwjiang007/alluxio,Reidddddd/mo-alluxio,riversand963/alluxio,Reidddddd/mo-alluxio,jsimsa/alluxio,apc999/alluxio,jswudi/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,uronce-cc/alluxio,jsimsa/alluxio,maboelhassan/alluxio,apc999/alluxio,ChangerYoung/alluxio,bf8086/alluxio,apc999/alluxio,maobaolong/alluxio,jswudi/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,Alluxio/alluxio,jswudi/alluxio,PasaLab/tachyon,calvinjia/tachyon,Alluxio/alluxio,jswudi/alluxio,uronce-cc/alluxio,Reidddddd/alluxio,ShailShah/alluxio,yuluo-ding/alluxio,uronce-cc/alluxio,ShailShah/alluxio,bf8086/alluxio,Alluxio/alluxio,aaudiber/alluxio,jsimsa/alluxio,maobaolong/alluxio,maboelhassan/alluxio,Reidddddd/alluxio,ChangerYoung/alluxio,bf8086/alluxio,aaudiber/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,ShailShah/alluxio,maboelhassan/alluxio,riversand963/alluxio,EvilMcJerkface/alluxio,WilliamZapata/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio,yuluo-ding/alluxio,madanadit/alluxio,bf8086/alluxio,Alluxio/alluxio,maboelhassan/alluxio,madanadit/alluxio,madanadit/alluxio,aaudiber/alluxio,aaudiber/alluxio,ChangerYoung/alluxio,maobaolong/alluxio,PasaLab/tachyon,Reidddddd/mo-alluxio | /*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.client.file;
import java.util.List;
import tachyon.annotation.PublicApi;
import tachyon.thrift.FileInfo;
/**
* Wrapper around {@link FileInfo}. Represents the metadata about a file or directory in Tachyon.
* This is a snapshot of information about the file or directory and not all fields are guaranteed
* to be up to date. Fields documented as immutable will always be accurate, and fields
* documented as mutable may be out of date.
*/
@PublicApi
public class URIStatus {
private final FileInfo mInfo;
/**
* Constructs an instance of this class from a {@link FileInfo}
* @param info an object containing the information about a particular uri
*/
public URIStatus(FileInfo info) {
mInfo = info;
}
/**
* @return a list of block ids belonging to the file, empty for directories, immutable
*/
public List<Long> getBlockIds() {
return mInfo.getBlockIds();
}
/**
* @return the default block size for this file, 0 for directories, immutable
*/
public long getBlockSizeBytes() {
return mInfo.getBlockSizeBytes();
}
/**
* @return the epoch time the entity referenced by this uri was created, immutable
*/
public long getCreationTimeMs() {
return mInfo.getCreationTimeMs();
}
/**
* @return the unique identifier of the entity referenced by this uri used by Tachyon servers,
* immutable
*/
public long getFileId() {
return mInfo.getFileId();
}
/**
* @return the group that owns the entity referenced by this uri, mutable
*/
public String getGroupName() {
return mInfo.getGroupName();
}
/**
* @return the percentage of blocks in Tachyon memory tier storage, mutable
*/
public int getInMemoryPercentage() {
return mInfo.getInMemoryPercentage();
}
/**
* @return the epoch time the entity referenced by this uri was last modified, mutable
*/
public long getLastModificationTimeMs() {
return mInfo.getLastModificationTimeMs();
}
/**
* @return the length in bytes of the file, 0 for directories, mutable
*/
public long getLength() {
return mInfo.getLength();
}
/**
* @return the last path component of the entity referenced by this uri, mutable
*/
public String getName() {
return mInfo.getName();
}
/**
* @return the entire path component of the entity referenced by this uri, mutable
*/
public String getPath() {
return mInfo.getPath();
}
/**
* @return the int representation of the ACL permissions of the entity referenced by this uri,
* mutable
*/
public int getPermission() {
return mInfo.getPermission();
}
/**
* @return the time-to-live in milliseconds since the creation time of the entity referenced by
* this uri, mutable
*/
public long getTtl() {
return mInfo.getTtl();
}
/**
* @return the uri of the under storage location of the entity referenced by this uri, mutable
*/
public String getUfsPath() {
return mInfo.getUfsPath();
}
/**
* @return the user which owns the entity referenced by this uri, mutable
*/
public String getUsername() {
return mInfo.getUserName();
}
}
| clients/unshaded/src/main/java/tachyon/client/file/URIStatus.java | /*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.client.file;
import java.util.List;
import tachyon.annotation.PublicApi;
import tachyon.thrift.FileInfo;
/**
* Wrapper around {@link FileInfo}. Represents the metadata about a file or directory in Tachyon.
* This is a snapshot of information about the file or directory and not all fields are guaranteed
* to be up to date. Fields documented as immutable will always be accurate, and fields
* documented as mutable may be out of date.
*/
@PublicApi
public class URIStatus {
private final FileInfo mInfo;
/**
* Constructs an instance of this class from a {@link FileInfo}
* @param info an object containing the information about a particular uri
*/
public URIStatus(FileInfo info) {
mInfo = info;
}
/**
* @return a list of block ids belonging to the file, empty for directories, immutable
*/
public List<Long> getBlockIds() {
return mInfo.getBlockIds();
}
/**
* @return the default block size for this file, 0 for directories, immutable
*/
public long getBlockSizeBytes() {
return mInfo.getBlockSizeBytes();
}
/**
* @return the epoch time the entity referenced by this uri was created, immutable
*/
public long getCreationTimeMs() {
return mInfo.getCreationTimeMs();
}
/**
* @return the unique identifier of the entity referenced by this uri used by Tachyon servers,
* immutable
*/
public long getFileId() {
return mInfo.getFileId();
}
/**
* @return the group that owns the entity referenced by this uri, mutable
*/
public String getGroupName() {
return mInfo.getGroupName();
}
/**
* @return the percentage of blocks in Tachyon memory tier storage, mutable
*/
public int getInMemoryPercentage() {
return mInfo.getInMemoryPercentage();
}
/**
* @return the epoch time the entity referenced by this uri was last modified, mutable
*/
public long getLastModificationTimeMs() {
return mInfo.getLastModificationTimeMs();
}
/**
* @return the length in bytes of the file, 0 for directories, mutable
*/
public long getLength() {
return mInfo.getLength();
}
/**
* @return the last path component of the entity referenced by this uri, mutable
*/
public String getName() {
return mInfo.getName();
}
/**
* @return the entire path component of the entity referenced by this uri
*/
public String getPath() {
return mInfo.getPath();
}
/**
* @return the int representation of the ACL permissions of the entity referenced by this uri
*/
public int getPermission() {
return mInfo.getPermission();
}
/**
* @return the time-to-live in milliseconds since the creation time of the entity referenced by
* this uri
*/
public long getTtl() {
return mInfo.getTtl();
}
/**
* @return the uri of the under storage location of the entity referenced by this uri
*/
public String getUfsPath() {
return mInfo.getUfsPath();
}
/**
* @return the user which owns the entity referenced by this uri
*/
public String getUsername() {
return mInfo.getUserName();
}
}
| Update docs for immutable/mutable fields in uri status.
| clients/unshaded/src/main/java/tachyon/client/file/URIStatus.java | Update docs for immutable/mutable fields in uri status. |
|
Java | apache-2.0 | e091f674acb7bb3aca7b3f904d0b383d08730728 | 0 | lesfurets/dOOv | /*
* Copyright (C) by Courtanet, All Rights Reserved.
*/
package io.doov.core.dsl.meta.ast;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import io.doov.core.dsl.lang.StepWhen;
import io.doov.core.dsl.meta.*;
public class AstLinePercentVisitor extends AstLineVisitor {
private static final NumberFormat formatter = new DecimalFormat("###.#");
private boolean endNary;
public AstLinePercentVisitor(StringBuilder stringBuilder, ResourceProvider bundle, Locale locale) {
super(stringBuilder, bundle, locale);
}
@Override
public void startMetadata(StepWhen metadata, int depth) {
sb.append(percentage((PredicateMetadata) metadata.stepCondition().getMetadata())+ " ");
super.startMetadata(metadata, depth);
}
@Override
public void startMetadata(BinaryMetadata metadata, int depth) {
super.startMetadata(metadata, depth);
if (metadata.children().get(0).type() == MetadataType.NARY_PREDICATE) {
sb.append(percentage(metadata));
}
}
@Override
public void startMetadata(NaryMetadata metadata, int depth) {
sb.append(formatCurrentIndent());
sb.append(bundle.get(metadata.getOperator(), locale));
sb.append(formatNewLine());
System.out.println(metadata.getOperator());
if (metadata.getOperator() != DefaultOperator.count && metadata.getOperator() != DefaultOperator.count) {
sb.append(percentage(metadata));
}
sb.append("[");
}
@Override
protected void endMetadata(NaryMetadata metadata, int depth) {
super.endMetadata(metadata, depth);
endNary = true;
}
@Override
protected String formatLeafMetadata(LeafMetadata metadata) {
if (stackPeek() == MetadataType.BINARY_PREDICATE) {
return super.formatLeafMetadata(metadata);
}
return percentage(metadata) + super.formatLeafMetadata(metadata);
}
private String percentage(PredicateMetadata metadata) {
int t = metadata.trueEvalCount();
int f = metadata.falseEvalCount();
if (f == 0 && t == 0) {
return "[n/a]";
}
else{
return "[" + formatter.format((t / ((double) t + f))*100) + "]";
}
}
}
| core/src/main/java/io/doov/core/dsl/meta/ast/AstLinePercentVisitor.java | /*
* Copyright (C) by Courtanet, All Rights Reserved.
*/
package io.doov.core.dsl.meta.ast;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import io.doov.core.dsl.lang.StepWhen;
import io.doov.core.dsl.meta.*;
public class AstLinePercentVisitor extends AstLineVisitor {
private static final NumberFormat formatter = new DecimalFormat("###.#");
public AstLinePercentVisitor(StringBuilder stringBuilder, ResourceProvider bundle, Locale locale) {
super(stringBuilder, bundle, locale);
}
@Override
public void startMetadata(StepWhen metadata, int depth) {
sb.append(percentage((PredicateMetadata) metadata.stepCondition().getMetadata())+ " ");
super.startMetadata(metadata, depth);
}
@Override
public void startMetadata(NaryMetadata metadata, int depth) {
sb.append(formatCurrentIndent());
sb.append(bundle.get(metadata.getOperator(), locale));
sb.append(formatNewLine());
sb.append(percentage(metadata) +" ");
sb.append("[");
}
@Override
protected String formatLeafMetadata(LeafMetadata metadata) {
return super.formatLeafMetadata(metadata) +" "+ percentage(metadata);
}
private String percentage(PredicateMetadata metadata) {
int t = metadata.trueEvalCount();
int f = metadata.falseEvalCount();
if (f == 0 && t == 0) {
return "[n/a]";
}
else{
return "[" + formatter.format((t / ((double) t + f))*100) + "]";
}
}
}
| :bug: fix count sum percentages visualisation
| core/src/main/java/io/doov/core/dsl/meta/ast/AstLinePercentVisitor.java | :bug: fix count sum percentages visualisation |
|
Java | apache-2.0 | 0e5c36c28e6554f8054ee37f61c97aaa364edcd2 | 0 | juanavelez/hazelcast,emre-aydin/hazelcast,lmjacksoniii/hazelcast,juanavelez/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,Donnerbart/hazelcast,dsukhoroslov/hazelcast,tufangorel/hazelcast,dbrimley/hazelcast,Donnerbart/hazelcast,tkountis/hazelcast,mesutcelik/hazelcast,tombujok/hazelcast,emrahkocaman/hazelcast,mesutcelik/hazelcast,mdogan/hazelcast,mesutcelik/hazelcast,emrahkocaman/hazelcast,dbrimley/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,mdogan/hazelcast,Donnerbart/hazelcast,tombujok/hazelcast,mdogan/hazelcast,lmjacksoniii/hazelcast,emre-aydin/hazelcast,dbrimley/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast | /*
* Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.examples;
import com.hazelcast.core.*;
import com.hazelcast.logging.ILogger;
import com.hazelcast.monitor.LocalMapOperationStats;
import com.hazelcast.partition.Partition;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
public class SimpleMapTest {
public static final int STATS_SECONDS = 10;
public static int THREAD_COUNT = 40;
public static int ENTRY_COUNT = 10 * 1000;
public static int VALUE_SIZE = 1000;
public static int GET_PERCENTAGE = 40;
public static int PUT_PERCENTAGE = 40;
final static ILogger logger = Hazelcast.getLoggingService().getLogger("SimpleMapTest");
private static final String NAMESPACE = "default";
public static boolean parse(String... input) {
boolean load = false;
if (input != null && input.length > 0) {
for (String arg : input) {
arg = arg.trim();
if (arg.startsWith("t")) {
THREAD_COUNT = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("c")) {
ENTRY_COUNT = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("v")) {
VALUE_SIZE = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("g")) {
GET_PERCENTAGE = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("p")) {
PUT_PERCENTAGE = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("load")) {
load = true;
}
}
} else {
logger.log(Level.INFO, "Help: sh test.sh t200 v130 p10 g85 ");
logger.log(Level.INFO, " // means 200 threads, value-size 130 bytes, 10% put, 85% get");
logger.log(Level.INFO, "");
}
return load;
}
public static void main(String[] args) throws InterruptedException {
boolean load = parse(args);
logger.log(Level.INFO, "Starting Test with ");
printVariables();
ITopic<String> commands = Hazelcast.getTopic(NAMESPACE);
commands.addMessageListener(new MessageListener<String>() {
public void onMessage(Message<String> stringMessage) {
parse(stringMessage.getMessageObject());
printVariables();
}
});
ExecutorService es = Executors.newFixedThreadPool(THREAD_COUNT);
startPrintStats();
if(load)
load(es);
run(es);
}
private static void run(ExecutorService es) {
final IMap<String, byte[]> map = Hazelcast.getMap(NAMESPACE);
for (int i = 0; i < THREAD_COUNT; i++) {
es.execute(new Runnable() {
public void run() {
while (true) {
int key = (int) (Math.random() * ENTRY_COUNT);
int operation = ((int) (Math.random() * 100));
if (operation < GET_PERCENTAGE) {
map.get(String.valueOf(key));
} else if (operation < GET_PERCENTAGE + PUT_PERCENTAGE) {
map.put(String.valueOf(key), new byte[VALUE_SIZE]);
} else {
map.remove(String.valueOf(key));
}
}
}
});
}
}
private static void load(ExecutorService es) throws InterruptedException {
final IMap<String, byte[]> map = Hazelcast.getMap("default");
final Member thisMember = Hazelcast.getCluster().getLocalMember();
List<String> lsOwnedEntries = new LinkedList<String>();
for (int i = 0; i < ENTRY_COUNT; i++) {
final String key = String.valueOf(i);
Partition partition = Hazelcast.getPartitionService().getPartition(key);
if (thisMember.equals(partition.getOwner())) {
lsOwnedEntries.add(key);
}
}
final CountDownLatch latch = new CountDownLatch(lsOwnedEntries.size());
for (final String ownedKey : lsOwnedEntries) {
es.execute(new Runnable() {
public void run() {
map.put(ownedKey, new byte[VALUE_SIZE]);
latch.countDown();
}
});
}
latch.await();
}
private static void startPrintStats() {
final IMap<String, byte[]> map = Hazelcast.getMap("default");
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(STATS_SECONDS * 1000);
logger.log(Level.INFO, "cluster size:" + Hazelcast.getCluster().getMembers().size());
LocalMapOperationStats mapOpStats = map.getLocalMapStats().getOperationStats();
long period = ((mapOpStats.getPeriodEnd() - mapOpStats.getPeriodStart()) / 1000);
if (period == 0) {
continue;
}
logger.log(Level.INFO, mapOpStats.toString());
logger.log(Level.INFO, "Operations per Second : " + mapOpStats.total() / period);
} catch (InterruptedException ignored) {
return;
}
}
}
});
}
private static void printVariables() {
logger.log(Level.INFO, " Thread Count: " + THREAD_COUNT);
logger.log(Level.INFO, " Entry Count: " + ENTRY_COUNT);
logger.log(Level.INFO, " Value Size: " + VALUE_SIZE);
logger.log(Level.INFO, " Get Percentage: " + GET_PERCENTAGE);
logger.log(Level.INFO, " Put Percentage: " + PUT_PERCENTAGE);
logger.log(Level.INFO, " Remove Percentage: " + (100 - (PUT_PERCENTAGE + GET_PERCENTAGE)));
}
}
| hazelcast/src/main/java/com/hazelcast/examples/SimpleMapTest.java | /*
* Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.examples;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.IMap;
import com.hazelcast.core.Member;
import com.hazelcast.logging.ILogger;
import com.hazelcast.monitor.LocalMapOperationStats;
import com.hazelcast.partition.Partition;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
public class SimpleMapTest {
public static final int STATS_SECONDS = 10;
public static int THREAD_COUNT = 40;
public static int ENTRY_COUNT = 10 * 1000;
public static int VALUE_SIZE = 1000;
public static int GET_PERCENTAGE = 40;
public static int PUT_PERCENTAGE = 40;
public static void main(String[] args) throws InterruptedException {
final ILogger logger = Hazelcast.getLoggingService().getLogger("SimpleMapTest");
boolean load = false;
if (args != null && args.length > 0) {
for (String arg : args) {
arg = arg.trim();
if (arg.startsWith("t")) {
THREAD_COUNT = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("c")) {
ENTRY_COUNT = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("v")) {
VALUE_SIZE = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("g")) {
GET_PERCENTAGE = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("p")) {
PUT_PERCENTAGE = Integer.parseInt(arg.substring(1));
} else if (arg.startsWith("load")) {
load = true;
}
}
} else {
logger.log(Level.INFO, "Help: sh test.sh t200 v130 p10 g85 ");
logger.log(Level.INFO, " // means 200 threads, value-size 130 bytes, 10% put, 85% get");
logger.log(Level.INFO, "");
}
logger.log(Level.INFO, "Starting Test with ");
logger.log(Level.INFO, " Thread Count: " + THREAD_COUNT);
logger.log(Level.INFO, " Entry Count: " + ENTRY_COUNT);
logger.log(Level.INFO, " Value Size: " + VALUE_SIZE);
logger.log(Level.INFO, " Get Percentage: " + GET_PERCENTAGE);
logger.log(Level.INFO, " Put Percentage: " + PUT_PERCENTAGE);
logger.log(Level.INFO, " Remove Percentage: " + (100 - (PUT_PERCENTAGE + GET_PERCENTAGE)));
ExecutorService es = Executors.newFixedThreadPool(THREAD_COUNT);
final IMap<String, byte[]> map = Hazelcast.getMap("default");
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
while (true) {
try {
//noinspection BusyWait
Thread.sleep(STATS_SECONDS * 1000);
logger.log(Level.INFO, "cluster size:" + Hazelcast.getCluster().getMembers().size());
LocalMapOperationStats mapOpStats = map.getLocalMapStats().getOperationStats();
long period = ((mapOpStats.getPeriodEnd() - mapOpStats.getPeriodStart()) / 1000);
if (period == 0) {
continue;
}
logger.log(Level.INFO, mapOpStats.toString());
logger.log(Level.INFO, "Operations per Second : " + mapOpStats.total() / period);
} catch (InterruptedException ignored) {
return;
}
}
}
});
if (load) {
final Member thisMember = Hazelcast.getCluster().getLocalMember();
List<String> lsOwnedEntries = new LinkedList<String>();
for (int i = 0; i < ENTRY_COUNT; i++) {
final String key = String.valueOf(i);
Partition partition = Hazelcast.getPartitionService().getPartition(key);
if (thisMember.equals(partition.getOwner())) {
lsOwnedEntries.add(key);
}
}
final CountDownLatch latch = new CountDownLatch(lsOwnedEntries.size());
for (final String ownedKey : lsOwnedEntries) {
es.execute(new Runnable() {
public void run() {
map.put(ownedKey, new byte[VALUE_SIZE]);
latch.countDown();
}
});
}
latch.await();
}
for (int i = 0; i < THREAD_COUNT; i++) {
es.execute(new Runnable() {
public void run() {
while (true) {
int key = (int) (Math.random() * ENTRY_COUNT);
int operation = ((int) (Math.random() * 100));
if (operation < GET_PERCENTAGE) {
map.get(String.valueOf(key));
} else if (operation < GET_PERCENTAGE + PUT_PERCENTAGE) {
map.put(String.valueOf(key), new byte[VALUE_SIZE]);
} else {
map.remove(String.valueOf(key));
}
}
}
});
}
}
}
| Advanced SimpleMapTest
git-svn-id: 505f71283407c412190d59965c6d67c623df2891@2560 3f8e66b6-ca9d-11dd-a2b5-e5f827957e07
| hazelcast/src/main/java/com/hazelcast/examples/SimpleMapTest.java | Advanced SimpleMapTest |
|
Java | apache-2.0 | 5f94d3a8ddcd4f14f581bcfd93449b708d5e1ec8 | 0 | angelograziano/repositoryJankins,gamalapa/simple-mvn-project,angelograziano/repositoryJankins,marleenkock/simple-mvn-project,anuragagrawal1/simple-mvn-project,dhinojosa/simple-mvn-project,dhinojosa/simple-mvn-project,chaitanya4u/simple-mvn-project,gamalapa/simple-mvn-project,anuragagrawal1/simple-mvn-project,marleenkock/simple-mvn-project,chaitanya4u/simple-mvn-project | package com.evolutionnext.model;
import com.evolutionnext.model.Album;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
public class AlbumTest {
@Test
public void testProperties() throws Exception {
Album album = new Album();
album.setName("Rumours");
album.setId(13L);
assertThat(album.getName()).isEqualTo("Hotel California");
assertThat(album.getId()).isEqualTo(13L);
}
}
| simple-maven-common/src/test/java/com/evolutionnext/model/AlbumTest.java | package com.evolutionnext.model;
import com.evolutionnext.model.Album;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
public class AlbumTest {
@Test
public void testProperties() throws Exception {
Album album = new Album();
album.setName("Rumours");
album.setId(13L);
assertThat(album.getName()).isEqualTo("Rumours");
assertThat(album.getId()).isEqualTo(13L);
}
}
| Update AlbumTest.java
Manually breaking the test, that's how I roll | simple-maven-common/src/test/java/com/evolutionnext/model/AlbumTest.java | Update AlbumTest.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.